如何对记录进行分组日期和用户

时间:2015-12-16 06:06:54

标签: sql-server tsql group-by

我有以下格式的查询表

Date       | Status     | Username
01-Jan-2015| May Join   | John
01-Jan-2015| Interested | David
02-Jan-2015| Interested | John
02-Jan-2015| Interested | David
02-Jan-2015| Interested | John

我需要生成相同的用户基础报告,直到现在我写了相同的查询。但我需要基于同样的报告来定义状态分解

Date        | Username | Interested | May Join
01-Jan-2015 | John     |     0      |   1
02-Jan-2015 | John     |     2      |   0

我的查询现在:

select Date = convert(date,CONVERT(nvarchar(10),Log,101)), Interested = COUNT(Status), May_Join=(Status) from tblenquiry where convert(date,CONVERT(nvarchar(10),Log,101)) between '01-Jan-15' and '02-jan-15' and User_ID='John' group by convert(date,CONVERT(nvarchar(10),Log,101))

请告知并提供帮助

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合执行此操作:

SELECT
    Date,
    Username,
    Interested  = SUM(CASE WHEN Status = 'Interested' THEN 1 ELSE 0 END),
    [May Join]  = SUM(CASE WHEN Status = 'May Join' THEN 1 ELSE 0 END)
FROM Enquiry
GROUP BY Date, Username