Mysql - 按月计数元素

时间:2014-02-11 12:42:10

标签: mysql sql

我有一张桌子,他跟随着以下字段:

-id---start_date(datetime)---end_date(datetime)-
-1---02/11/13 4:00---02/11/13 5:00-
-2---02/12/13 4:00---02/12/13 5:00-
-3---02/11/13 5:00---02/11/13 6:00-
-4---03/11/13 4:00---03/11/13 5:00-
-5---02/11/13 3:00---02/14/13 3:00-

我想计算一天中每天有多少条记录,从start_date开始到另一end_date结束。
例如,在02/10/13和03/10/13之间选择:

-count---day(datetime)-
-3---02/11/13-
-2---02/12/13-
-1---02/13/13-
-1---02/14/14-

谢谢!
如果我想在主表中添加一个字段与每个记录的频率?
例如:
频率
0:一次性;
1:每天;
7:每周;
等...

 -id---start_date(datetime)---end_date(datetime)---frequency-
-1---02/11/13 4:00---02/11/13 5:00---7-
-2---02/12/13 4:00---02/12/13 5:00---0-
-3---02/11/13 5:00---02/11/13 6:00---0-
-4---03/11/13 4:00---03/11/13 5:00---0-
-5---02/11/13 3:00---02/14/13 3:00---0-

结果:

-count---day(datetime)-
-3---02/11/13-
-2---02/12/13-
-1---02/13/13-
-1---02/14/14-
-1---02/18/14-
-1---02/25/14-
-1---03/04/14-

1 个答案:

答案 0 :(得分:0)

对数据格式和表格做出一些假设: -

SELECT aDate, COUNT(SomeDateTable.id)
FROM
(
    SELECT DATE_ADD("2013-02-10", INTERVAL (Hundreds.i * 100 + Tens.i * 10 + Units.i) DAY) AS aDate
    FROM
    (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Units,
    (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Tens,
    (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) Hundreds
    WHERE DATE_ADD("2013-02-10", INTERVAL (Hundreds.i * 100 + Tens.i * 10 + Units.i) DAY) <= "2013-03-10"
) sub1
INNER JOIN SomeDateTable
ON sub1.aDate BETWEEN DATE(SomeDateTable.start_date) AND DATE(SomeDateTable.end_date)
GROUP BY aDate;

这将处理最多1000天的日期范围

SQL在这里小提琴: -

http://www.sqlfiddle.com/#!2/103b7/1