各种时间段的SQL查询

时间:2013-07-24 09:13:41

标签: mysql

enter image description here

我有一个包含以下条目的表:

completed_time||   BOOK_CNT
*********************************************
2013-07-23    | 2
2013-07-22    | 1
2013-07-19    | 3
2013-07 16    |5
2013-07-12    |4
2013-07-11    |2
2013-07-02    |9
2013-06-30    |5

现在,我想使用上面的条目进行数据分析。

让我们说DAYS_FROM,DAYS_TO和PERIOD是三个变量。

我需要点击以下类型的查询:

在PERIOD区间内从DAYS_FROM到DAYS_TO的总图书。

DAYS_FROM 是格式为YYYY-MM-DD的日期

DAYS_TO 是格式为YYYY-MM-DD的日期

PERIOD 是{1W,2W,1M,2M,1Y}  其中W,M,Y代表WEEK,MONTH和YEAR。

示例:查询DAYS_FROM = 2013-07-23,DAYS_TO = 2013-07-03和PERIOD = 1W应返回:

ith week - total
1 -        3
2-         8
3-         6 
4-         14

解释

1-3 means (The total book from 2013-07-21(sun) to 2013-07-23(tue) is 3 )
2-8 means (The total book from 2013-07-14(sun) to 2013-07-21(sun) is 8 )
3-16 means (The total book from 2013-07-07(sun) to 2013-07-14(sun) is 6 )
4-14 means (The total book from 2013-07-03(wed) to 2013-07-07(sun) is 14 )

请参阅日历图片以便更好地理解

如何触发此类查询?

我尝试了什么?

 SELECT DAY(completed_time), COUNT(total) AS Total
  FROM my_tab
 WHERE completed_time BETWEEN '2013-07-23' - INTERVAL 1 WEEK AND '2013-07-03'
 GROUP BY DAY(completed_time);

以上查询从2013-07-23减去7天后被视为 2013-07-16至2013-07-23 第一周 2013-07-09至2013-07-16 第二周等等。

1 个答案:

答案 0 :(得分:1)

一个简单的起点如下所示,当然您可能需要调整ith值以满足您的需求;

SET @period='1M';

SELECT CASE WHEN @period='1Y' THEN YEAR(completed_time) 
            WHEN @period='1M' THEN YEAR(completed_time)*100+MONTH(completed_time)
            WHEN @period='2M' THEN FLOOR((YEAR(completed_time)*100+MONTH(completed_time))/2)*2
            WHEN @period='1W' THEN YEARWEEK(completed_time)
            WHEN @period='2W' THEN FLOOR(YEARWEEK(completed_time)/2)*2
       END ith,
       SUM(BOOK_CNT) Total
FROM my_tab
GROUP BY ith
ORDER BY ith DESC;

An SQLfiddle to test with