计算不同年份的每半年的行数

时间:2014-03-23 10:03:30

标签: mysql count

我想计算过去半年每个月的ID数量,这是我的查询:

SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE) UNION SELECT `count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH) UNION SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 2 MONTH) UNION SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 3 MONTH) UNION SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 4 MONTH) UNION SELECT count(`Id`) FROM `items` WHERE MONTH(Created) = MONTH(CURRENT_DATE - INTERVAL 5 MONTH);`

Created是已创建行的时间戳。

我的问题是第四个月,第五个月和第六个月。因为它们是在2013年(不同年份)创建的,所以我的查询无法获得结果。

1 个答案:

答案 0 :(得分:4)

我会从这样的事情开始:

SELECT MONTH(created), count(*)
FROM `items`
WHERE Created >= LAST_DAY(current_date() - INTERVAL 6 MONTH) + INTERVAL 1 DAY
GROUP BY MONTH(created)

LAST_DAY(current_date() - INTERVAL 6 MONTH) + INTERVAL 1 DAY将在月份的第一天返回开始计算的位置,您可能还希望按月和年分组:

SELECT DATE_FORMAT(created, '%Y-%m'), count(*)
FROM `items`
WHERE Created >= LAST_DAY(current_date() - INTERVAL 6 MONTH) + INTERVAL 1 DAY
GROUP BY DATE_FORMAT(created, '%Y-%m')