SQL新日常表基于日期范围

时间:2013-09-28 17:42:48

标签: mysql sql

我有以下查询:

root@localhost [hatsize]> SELECT COUNT(*) AS C,EventID,Start,End,sysname  FROM complete_ev WHERE type = 's' AND EventID = 6881;
+----+---------+---------------------+---------------------+---------+
| C  | EventID | Start               | End                 | sysname |
+----+---------+---------------------+---------------------+---------+
| 26 |    6881 | 2013-09-09 12:00:00 | 2013-09-13 22:00:00 | sv-esx4 |
+----+---------+---------------------+---------------------+---------+

我想创建一个包含Count,EventID和sysname的新表,但是我希望每天的日期如下:

 26 6881   2013-09-09  sv-esx4
 26 6881   2013-09-10  sv-esx4
 26 6881   2013-09-11  sv-esx4
 26 6881   2013-09-12  sv-esx4
 26 6881   2013-09-13  sv-esx4

谁能告诉我怎么做?我尝试过一些东西,但没有提出正确的配方。 感谢。

1 个答案:

答案 0 :(得分:1)

您需要一个驱动程序表来查找您要查找的日期范围(您可以使用子查询或CTE,但是完整的表值得付出努力)。创建日历表将是在性能方面执行此操作的最佳方式。如果需要,您可以找到大量的固定SQL脚本来创建日历表。该资源将随时派上用场,因此非常值得花费最少的设置工作量。假设您有一个日历表,则可以执行以下操作:

SELECT allEvents.totalCount AS C,
  ev.EventID,
  CAST(c.Date AS Date) AS date,
  ev.sysname  
FROM complete_ev ev
RIGHT JOIN calendar c ON c.Date BETWEEN ev.Start AND ev.End
INNER JOIN (SELECT COUNT(EventID) AS totalCount, EventID FROM complete_ev GROUP BY EventID) AS allEvents ON ev.EventID = allEvents.eventID
WHERE ev.type = 's' 
  AND ev.EventID = 6881;
事实上这是票。祝你好运。