MySQL特定的查询要求

时间:2010-11-24 11:47:58

标签: datetime mysql

我在“sales”表中有datetime字段名称“salestime”

我需要获取数据:

SalesMonthYear      Total
2010-11             10
2010-10             15
2010-09             21

Nov-2010            10
Oct-2010            15
Sep-2010            21

任何人都知道如何使用查询实现此目的? 谢谢你的帮助

2 个答案:

答案 0 :(得分:1)

您需要使用DATE_FORMATGROUP BY来实现您的目标。此查询将执行此操作:

SELECT DATE_FORMAT(salestime, '%Y-%m') as SalesMonthYear, count(*) as `Total` FROM `sales` GROUP BY SalesMonthYear ORDER BY `salestime`

对于第二个版本:

SELECT DATE_FORMAT(salestime, '%b-%Y') as SalesMonthYear, count(*) as `Total` FROM `sales` GROUP BY SalesMonthYear ORDER BY `salestime`

答案 1 :(得分:0)

SELECT DATE_FORMAT(salesTime, '%Y-%m') AS salesMonthYear,
       COUNT(*) AS salesCount
FROM sales
GROUP BY DATE_FORMAT(salesTime, '%Y-%m')