我有一个查询,可以在特定课程中为学员生成结果,显示他们是否已完成模块。学习者可以互相采用不同的模块。
SELECT LearnerID,
UnitID,
CASE WHEN (SUM(Total - [Total Achieved])) = 0 THEN 'Yes' ELSE 'No' END AS Completed
FROM dbo.LMS_Achieved_Standards_Report
GROUP BY CourseID, LearnerID, UnitID
结果看起来像这样
LearnerID UnitID Completed
15 15 Yes
15 28 No
28 28 Yes
116 150 Yes
79 12 No
69 34 Yes
69 15 No
我需要它看起来像这样:
LearnerID Unit 15 Unit 28 Unit 150 Unit 12 Unit 34
15 Yes No
28 Yes
116 Yes
79 Yes
69 No Yes
已经陈述的另一个因素是它们都可以采用不同的单位,因此我无法创建具有设置列标题的PIVOT。
有什么想法吗?
答案 0 :(得分:0)
试试这个;
select * into #tbl from (select 'cust1' as key1, 'Red'as Type
union select 'cust1' as key1, 'Blue'as Type
union select 'cust1' as key1, 'Yellow'as Type
union select 'cust2' as key1, 'Red'as Type
union select 'cust2' as key1, 'Blue'as Type
union select 'cust2' as key1, 'Green'as Type) as dd
declare @strsql as nvarchar(max)
declare @columns as nvarchar(max)
set @columns = (select stuff((select distinct ',['+Type+']' from #tbl FOR XML PATH('')),1,1,''))
set @strsql = 'select key1,'+@columns + 'from (select * from #tbl) as p pivot (count(p.Type) For p.Type in ('+@columns+'))as pivottable'
--set @strsql = 'select
EXECUTE sp_executesql @strsql