在SQL查询中按日期,日间隔分组

时间:2013-10-16 01:46:37

标签: sql nexusdb

假设我有一个类似于以下(简化)的表:

| Name  | Date     | Hours |
| Bob   | 10/1/13  |  5    |
| John  | 10/1/13  |  8    |
| Bob   | 10/2/13  |  6    |
| Ashley| 10/2/13  |  4    |
...
| Bob   | 10/17/13 |  4    |
| John  | 10/17/13 |  6    |
| John  | 10/18/13 |  3    |
...

给定开始日期(例如10/1/13),如何构建查询以将名称,SUM(小时)分组14天?所以结果会是这样的:

| Name  | Period              | SUM(Hours) |
| Bob   | 10/1/13 - 10/14/13  |  11        |
| John  | 10/1/13 - 10/14/13  |  8         |
| Ashley| 10/1/13 - 10/14/13  |  4         |
| Bob   | 10/15/13 - 10/29/13 |  4         |
| John  | 10/15/13 - 10/29/13 |  9         |

我已尝试过帖子中列出的建议,例如:Group by date range on weeks/months interval 但他们通常认为你想要实际的周。由于这些只是间隔14天,因此不一定与一年中的几周保持一致。

任何建议或指导都赞赏!

编辑:这是查询NexusDB服务器,因此它使用SQL:2003标准。

1 个答案:

答案 0 :(得分:3)

这可能是这样的吗? (假设它是MySQL)

更新:在SQL Fiddle中测试过(感谢@ pm-77-1):http://sqlfiddle.com/#!2/3d7af/2

谨慎之处:由于我们在这里进行日期算术这一事实,如果它将在大型表上运行,则此查询可能会变得很重。

SELECT Name, 
CONCAT(DATE_ADD(<your-starting-date>, INTERVAL period*14 day),
" - ",
DATE_ADD(<your-starting-date>, INTERVAL period*14+13 day)) as Period,
Hours FROM 
(SELECT Name, 
FLOOR(DATEDIFF(Date,<your-starting-date>)/14) AS period, 
SUM(Hours) as Hours 
FROM <yourtable> GROUP BY period, name) p;

NexusDB的更新。我在NexusDB中找到了DateDiff替换的一些信息:

http://www.nexusdb.com/support/index.php?q=node/10091

考虑到这一点,您有两种选择:要么将该功能添加到数据库中,要么不必修改查询,要么用该定义替换DATEDIFF:

SELECT Name, 
CONCAT(DATE_ADD(<your-starting-date>, INTERVAL period*14 day),
" - ",
DATE_ADD(<your-starting-date>, INTERVAL period*14+13 day)) as Period,
Hours FROM 
(SELECT Name, 
FLOOR(cast((cast(Date as float ) - cast(<your-starting-date> as float)) as integer)/14) as period,
SUM(Hours) as Hours 
FROM <yourtable> GROUP BY period, name) p;