SQL查询按日期时间分组并获取其他2个字段的总值

时间:2015-11-28 12:11:39

标签: sql datetime group-by totals

我在编写将日期时间列(修改)分组为几天的sql查询时遇到问题,并且每天给我计算另一个字段的值,状态可以是1或2.

我尝试过只计算状态= 1,但即使这样也没有给出我想要的东西:

SELECT DateValue([a.Modified]) AS Expr1, Count(b.Modified) AS Total
FROM MyTable AS a LEFT JOIN (SELECT Modified FROM MyTable WHERE Status = 1)  AS b ON 
a.Modified = b.Modified
GROUP BY DateValue([a.Modified]);

以下是一些示例数据和我想要的结果。

Modified             Status

01-10-2004 20:17:00    1

01-10-2004 20:17:00    2

02-10-2004 11:53:31    1

02-10-2004 11:53:31    2

02-10-2004 11:55:26    2

02-10-2004 11:55:26    1

02-10-2004 12:00:56    2

02-10-2004 12:02:39    2

02-10-2004 12:04:28    1

02-10-2004 12:04:28    2

02-10-2004 12:06:18    2

02-10-2004 12:08:19    1

02-10-2004 12:08:19    2

02-10-2004 12:09:50    2

02-10-2004 12:09:50    1

02-10-2004 12:11:21    2

02-10-2004 12:11:22    1

02-10-2004 12:12:41    2

02-10-2004 12:12:41    1

03-10-2004 09:27:20    1

03-10-2004 09:27:20    2

预期结果:

Modified    Status1Count    Status2Count

02-10-2004     7               10 

1 个答案:

答案 0 :(得分:0)

这应该可以满足您的需求:

SELECT 
    CAST(Modified AS DATE) AS DateValue, 
    SUM(CASE WHEN [Status] = 1 THEN 1 ELSE 0 END) AS Status1Count,
    SUM(CASE WHEN [Status] = 2 THEN 1 ELSE 0 END) AS Status2Count    
FROM MyTable
GROUP BY 
    CAST(Modified AS DATE)