我在SQL Server 2008 R2中有两个表: 表“阶段:
Phases_ID Phases_Title
------------------------
1 Phase1
2 Phase2
... ...
和表“里程碑”
Milestones_ID Milestones_PhaseID Milestones_Category
------------------------------------------------------
1 1 Project
2 1 Project
3 1 Customer
... ... ...
你可以看到这是表之间的1:n关系。
现在我需要一个结果类似的查询:
Phases_ID Project Customer (Columns 'Project' and 'Customer' counts milestones)
---------------------------------
1 2 1
2 0 3
... ... ...
是否有可能动态创建带有里程碑类别的列? 否则我将在表格上做一个简单的左连接,然后在代码中执行其余操作,但性能将是最差的。
谢谢!
答案 0 :(得分:0)
是的! PIVOT
救援:http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
尝试这样的事情:
SELECT Phases_ID, Project, Customer
FROM (
SELECT Phases_ID, Milestones_PhaseID, Milestones_Category
FROM Phases INNER JOIN Milestones ON Phases_ID = Milestones_PhaseID
) AS src
PIVOT (
COUNT(*)
FOR Milestones_Category IN ([Project], [Customer])
) AS pvt