带有分组的SQL数据透视表

时间:2018-04-27 12:25:43

标签: sql sql-server

我有一张工作表,学生已根据要求做了工作,即

 Name  RequirementID RequirementType Completed
 Fred       1            Questions     1
 Fred       2            Portfolio     Null
 Fred       3            Questions     Null
 Fred       4            Portfolio     1
 Mary       1            Questions     Null
 Mary       2            Portfolio     1
 Mary       3            Questions     1
 Mary       4            Portfolio     1

我想将其放在数据透视表中,以便结果为:

Name   TotalRequired  Questions   Portfolio
Fred         4            1           1
Mary         4            1           2

我可以直截了当地获得“已完成”的总数。专栏,但我想知道是否有可能获得“TotalRequired”#39;我也是。

select * from (
select Name,RequirementID,RequirementType,Completed
from Course_Requirements) as s

PIVOT
(Count (Completed) for RequirementType in (Questions, Portfolio)
) as pvt

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我会使用条件聚合:

select name,
       count(*) as TotalRequired,
       count(case when RequirementType = 'Questions' then completed end) as Questions,
       count(case when RequirementType = 'Portfolio' then completed end) as Portfolio
from Course_Requirements cr
group by name;

答案 1 :(得分:1)

我打赌你可以使用COUNT() OVER

来做到这一点
select * from (
select Name,RequirementID,RequirementType,Completed,
TotalRequired=COUNT(*) OVER(PARTITION BY Name)
from Course_Requirements) as s

PIVOT
(Count (Completed) for RequirementType in (Questions, Portfolio)
) as pvt