2
我有3个表:如何创建Sql Server 2008交叉表动态查询?
- 位置:
LocationID, LocationName
- 缺陷:
DefectID, DefectType
- 反馈:
feedbackID, DefectID, LocationID
我需要在以下格式交叉表报告:地点栏下面的数字是防守总数cts为该位置。位置可以是任何数字。它应该是动态的..
DefectID DefectType NewYork NewJersey Texas Houston
1 Defect1 0 10 3 6
2 Defect2 0 0 9 10
3 Defect3 8 8 4 6
我有一个SQL查询是硬编码的。此外,它不显示DefectID
..
select
DefectType,
[1] as NewYork,
[4] as NewJersy,
[5] as Texas,
[6] as Houston
from (select
Defect.DefectID,
Defect.DefectType,
Location.LocationID
from Feedback
inner join Locations on (Feedback.LocationID= Location.LocationID)
inner join DefectType on (Feedback.DefectID= Defect.DefectID)
) p
pivot
(count (DefectID) for LocationID in ([1], [4], [5],[6]) ) as pvt
order by pvt.DefectType;