我对SQL很新。我构建了一个查询,以便每行指定一个事件的发生。这是一个示例(它存储在查询中的临时表中)。
Id Date Acct FirstName LastName
--------------------------------------------
123 2016-02-02 456789 Joan Smith
123 2016-02-03 456789 Joan Smith
456 2016-02-02 987654 John Adams
789 2016-02-04 123789 Matt James
789 2016-02-07 123789 Matt James
我想要做的是拿下该表并计算每个人发生事件的总次数,但也能够查看事件发生的日期。
所以决赛桌应该是这样的:
ID Acct FirstName LastName 2/1/2016 2/2/2016 2/3/2016 2/4/2016 2/5/2016 2/6/2016 2/7/2016 Total
123 456789 Joan Smith 1 1 2
456 987654 John Adams 1 1
789 123789 Matt James 1 1 2
我能够获得总出现次数,但我不知道如何将日期作为新列。 CASE
会有效吗?还是PIVOT
?我不确定如何使用这两个命令来实现这一目标。
这是我到目前为止构建的查询和输出
select
ID,
Acct,
FirstName,
LastName,
Count(Date) as Total
from
##tempTable
group by
Acct, PlayerID, FirstName, LastName
输出:
ID Acct FirstName LastName Total
-----------------------------------------
123 456789 Joan Smith 2
456 987654 John Adams 1
789 123789 Matt James 2
答案 0 :(得分:0)
如果你只关心那些日子,那么下面应该有效
select ID,
Acct,
FirstName,
LastName,
SUM(CASE WHEN [DATE] = '2016-02-01' THEN 1 ELSE NULL END) AS '2/1/2016',
SUM(CASE WHEN [DATE] = '2016-02-02' THEN 1 ELSE NULL END) AS '2/2/2016',
SUM(CASE WHEN [DATE] = '2016-02-03' THEN 1 ELSE NULL END) AS '2/3/2016',
SUM(CASE WHEN [DATE] = '2016-02-04' THEN 1 ELSE NULL END) AS '2/4/2016',
SUM(CASE WHEN [DATE] = '2016-02-05' THEN 1 ELSE NULL END) AS '2/5/2016',
SUM(CASE WHEN [DATE] = '2016-02-06' THEN 1 ELSE NULL END) AS '2/6/2016',
SUM(CASE WHEN [DATE] = '2016-02-07' THEN 1 ELSE NULL END) AS '2/7/2016',
Count(Date) as Total
from ##tempTable
group by Acct, ID, FirstName, LastName