如何在SQL Server中使用pivot来汇总和计算出勤率

时间:2017-07-06 14:11:32

标签: sql-server sql-server-2008 sql-server-2008-r2

我有一张表Mark_Attendance,它包含:

Class | [Status] | [DateTime]  | S_Adm_No  | Gender 
------+----------+-------------+-----------+--------
NUR   | P        | 2017-04-19  | 1101      | Male
NUR   | A        | 2017-04-19  | 1102      | Male
NUR   | P        | 2017-04-19  | 1103      | Female
NUR   | A        | 2017-04-19  | 1104      | Female
KG    | P        | 2017-04-19  | 1105      | Male
KG    | A        | 2017-04-19  | 1106      | Male
KG    | P        | 2017-04-19  | 1107      | Female
KG    | A        | 2017-04-19  | 1108      | Female

现在我想显示我的结果

Class|ttl|total_male|ttl_FeMale|Ttl_Pr|Pr_Male|Pr_Female|Ttl_Ab|Ab_Female|Ab_Mal2
NUR  |4  |  2       |   2      | 2    |2      | 2       |2     |2        |2
KG   |4  |  2       |   2      | 2    |2      | 2       |2     |2        |2

为了获得此结果,我应该在SQL Server中使用哪种查询。

1 个答案:

答案 0 :(得分:1)

当然你的输出是错误的

正确的查询和输出应为:

app.config.from_object('configmodule.ProductionConfig')

并输出应为:

select Class, Count(Class) as ttl,
Sum(Case when Gender = 'Male' Then 1 Else 0 End) as Total_Male,
Sum(Case when Gender = 'Female' Then 1 Else 0 End) as Total_Female,
Sum(Case when Status = 'P' Then 1 Else 0 End) as Total_Present,
Sum(Case when Status = 'P' and Gender = 'Male' Then 1 Else 0 End) as Total_Male_Present,
Sum(Case when Status = 'P' and Gender = 'Female' Then 1 Else 0 End) as Total_Female_Present,
Sum(Case when Status = 'A' Then 1 Else 0 End) as Total_Absent,
Sum(Case when Status = 'A' and Gender = 'Male' Then 1 Else 0 End) as Total_Male_Absent,
Sum(Case when Status = 'A' and Gender = 'Female' Then 1 Else 0 End) as Total_Female_Absent
from  Mark_Attendance
group by Class;

如果您想了解我是如何实现此结果的,请阅读

我强烈反对那些在没有表现出努力的情况下发帖提问的人。