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;