【发布时间】:2012-11-14 23:39:52
【问题描述】:
我有 3 张桌子:
-
地点:
LocationID, LocationName -
缺陷:
DefectID, DefectType -
反馈:
feedbackID, DefectID, LocationID
我需要以下格式的交叉表报告:位置列下方的数字是该位置的缺陷总数。位置可以是任意数字。它应该是动态的..
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;
【问题讨论】:
标签: sql sql-server-2008