有没有办法对两个日期之间的记录进行分组?
例如,我的表中的记录如下所示:
rid stamp uid
25 2005-07-05 14:10:29 25
1175 2005-08-12 15:47:35 29
290 2005-11-22 16:38:53 42
30 2005-12-01 10:48:12 47
30 2006-01-02 17:34:28 52
30 2006-02-06 22:11:35 57
30 2006-04-17 15:10:19 59
1195 2006-05-08 21:55:56 62
100 2006-06-30 15:51:04 94
45 2006-07-03 21:14:37 24
我正在尝试编写一个查询,该查询将在February - August
月份之间和September - January
之间按年返回记录计数,以便我得到的是:
July 2005 - January 2006: 3
February 2006 - August 2006: 5
答案 0 :(得分:9)
你可以在任何你想要的东西上进行分组。如果您可以在列中显示某些内容以显示您想要的内容,则可以对其进行分组。因此,对于仅两个时期,您可以简单地分组if:
SELECT * FROM table
GROUP BY if(stamp between "2005-07-01" and "2006-02-01", 0, 1)
如果您需要更长时间(多年)的期间,您可以使用period_diff来区分:
SELECT * FROM table
GROUP BY floor(period_diff( DATE_FORMAT(stamp, "%Y%m"), "200507") / 6)
它将以年 - 月格式为您提供在您的日期和开始期间之间传递的6个月块数。
答案 1 :(得分:3)
在其他人的轻微组合中...... 您可以根据需要扩展案例结构。该组尊重“序数”第1列位置,因此您不必在group by子句中复制相同的大小写条件。另外,我在Order by中加入了相同的上下文,因为否则会按字母顺序排序结果。您可以按照您想要的任何方式进行订购......如果您希望首先列出最新的当前日期活动,则可以反过来。
SELECT
case when stamp between "2005-07-01" and "2006-02-01"
then "July 2005 - January 2006 "
when stamp between "2006-02-01" and "2006-08-01"
then "February 2006 - August 2006"
else "After August 2006 "
end as GroupColumn,
count(*) as TotalPerGroup
from
table
where
date >= '2005-07-01'
group by
1
order by
case when stamp between "2005-07-01" and "2006-02-01"
then 1
when stamp between "2006-02-01" and "2006-08-01"
then 2
else 3
end
答案 2 :(得分:0)
如果只有一个组,那么你可以使用“with by with having子句”。我不认为有一种语法可以在一个语句中指定多个不同的分组并将它们分开。以下是我能想到的最简单的替代解决方案:
select "July 2005 - January 2006" AS "Date", count(date) as "results"
from MYTABLE
where date >= '2005-07-01' AND date <= '2006-01-31'
union
select "February 2006 - August 2006" AS "Date", count(date) as "results"
from MYTABLE
where date >= '2006-02-01' AND date <= '2006-08-31';