按月分组,并在日期为 yyyy-mm-dd 时进行汇总
我正在上 SQL 在线课程,我需要 yyyy-mm-dd 格式的日期。我需要按月分组以显示 MedalId 的总销售额和一个月内销售的总 MedalId。
我似乎无法设计一种使用这种格式汇总月份的方法。任何建议和指导将不胜感激:
SELECT date, COUNT(medalId) AS totalProducts, SUM(medalId) as totalSales
from orders
GROUP BY date WITH ROLLUP;
I'm doing an online course in SQL and I need to have date in yyyy-mm-dd format. I need to group by month to show total sales of medalId and total medalId sold in a month.
I just can't seem to be able to engineer a way to rollup with month using this format. Any advice and guidance would be really appreciated:
SELECT date, COUNT(medalId) AS totalProducts, SUM(medalId) as totalSales
from orders
GROUP BY date WITH ROLLUP;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MySQL 的列数据类型为
DATE
。使用它。尽量避免使用VARCHAR()
或CHAR()
列来保存日期。这是值得的,因为当你这样做时,你会得到很多很酷的日期算术。而且,它们排序正确。您的2020-03-25
格式与DATE
数据类型兼容。你想要这样的东西,使用 LAST_DAY() 日期算术函数。
专业提示:在进行数据库编程时,值得花时间学习 DBMS 的 日期/时间 和 字符串处理函数。
MySQL has the
DATE
datatype for columns. Use it. Take the trouble to avoid usingVARCHAR()
orCHAR()
columns to hold dates. It's worth it because you get a lot of cool date arithmetic when you do that. Also, they sort correctly. Your2020-03-25
format is compatible with theDATE
datatype.You want something like this, using the LAST_DAY() date-arithmetic function.
Pro tip: When doing database programming, it is worth your time to learn your DBMS's date/time and string processing functions.