我有一张这样的表
Employee Response Code
-------------------------
Emp A vml
Emp B wrn
Emp C ptb
Emp A wrn
Emp B ulm
Emp A vml
Emp B ulm
Emp C vml
我需要从上表
创建这样的报告 vml wrn ptb ulm
------------------------
Emp A 2 1 0 0
Emp B 0 1 0 2
Emp C 1 0 1 0
Totals 3 2 1 2
报告表计算每位员工的每个代码的计数,总计算结束时每列的总和
我该怎么做?有人可以帮帮我吗?非常感谢你的时间和帮助
答案 0 :(得分:3)
以下是两个选项:第一个是动态,它将允许将来的响应代码。第二个将说明实际的PIVOT语法
动态选项
Declare @SQL varchar(max)
Select @SQL = Stuff((Select Distinct ',' + QuoteName([Response Code]) From YourTable Order by 1 For XML Path('')),1,1,'')
Select @SQL = 'Select [Lvl],[Employee],' + @SQL + '
From (
Select [Employee],[Response Code],Cnt=1,Lvl=0 from YourTable
Union All
Select ''Total'',[Response Code],count(*),1 From YourTable Group By [Response Code]
) A
Pivot (sum(Cnt) For [Response Code] in (' + @SQL + ') ) p'
Exec(@SQL);
非动态选项
Select [Lvl],[Employee],[ptb],[ulm],[vml],[wrn]
From (
Select [Employee],[Response Code],Cnt=1,Lvl=0 from YourTable
Union All
Select 'Total',[Response Code],count(*),1 From YourTable Group By [Response Code]
) A
Pivot (sum(Cnt) For [Response Code] in ([ptb],[ulm],[vml],[wrn]) ) p
两者都会返回
Employee ptb ulm vml wrn
Emp A NULL NULL 2 1
Emp B NULL 2 NULL 1
Emp C 1 NULL 1 NULL
Total 1 2 3 2
编辑 - 删除NULL
注意额外的Union All
Declare @SQL varchar(max)
Select @SQL = Stuff((Select Distinct ',' + QuoteName([Response Code]) From YourTable Order by 1 For XML Path('')),1,1,'')
Select @SQL = 'Select [Lvl],[Employee],' + @SQL + '
From (
Select [Employee],[Response Code],Cnt=1,Lvl=0 from YourTable
Union All
Select [Employee],[Response Code],Cnt=0,Lvl=0 from (Select Distinct [Employee] from YourTable) A Join (Select Distinct [Response Code] from YourTable) B on 1=1
Union All
Select ''Total'',[Response Code],count(*),1 From YourTable Group By [Response Code]
) A
Pivot (sum(Cnt) For [Response Code] in (' + @SQL + ') ) p'
Exec(@SQL);
答案 1 :(得分:0)
根据您的上一条评论,您需要使用Dynamic Pivot,因为默认情况下,PIVOT运算符需要提供一个静态的列列表来进行透视。
请参阅我对类似问题的回答: How-to-convert-many-to-many-entity-relationship-to-tabular-view-in-sql
特别要注意动态枢轴部分。
如果您提到的答案太难理解,那么请搜索谷歌搜索SQL Server动态数据透视表。以下是一个示例结果:Script to create dynamic PIVOT queries in SQL Server
希望这会有所帮助。如果仍然遇到麻烦,请在评论中发布您尝试过的内容以及哪些内容无效。