我有一个结构如下的表:
ID | Type | PrimaryInd | SecondaryInd | TertiaryInd
---------------------------------------------------
12 | Boat | 0 | 1 | 0
12 | Auto | 1 | 1 | 1
12 | Home | 1 | 0 | 1
我正在尝试将每个ID的结果排成一行,如下所示:
ID | BoatPrimaryInd | BoatSecondaryInd | BoatTertiaryInd | AutoPrimaryInd | ...
-------------------------------------------------------------------------------
12 | 0 | 1 | 0 | 1 | ...
我目前使用CASE和GROUP BY来像这样设置查询:
SELECT
ID,
MIN(CASE WHEN Type = 'Boat' THEN PrimaryInd+0 END) AS BoatPrimaryInd,
...
FROM Table
GROUP BY ID
这是最有效的方法吗?我尝试查看了PIVOT表,但是由于我在这里没有任何汇总信息,因此我不确定这是我需要的东西。
答案 0 :(得分:3)
您可以与CROSS APPLY一起使用PIVOT
示例
Select *
From (
Select A.ID
,B.*
From YourTable A
Cross Apply ( values (concat([Type],'PrimaryInd') ,[PrimaryInd] )
,(concat([Type],'SecondaryInd'),[SecondaryInd])
,(concat([Type],'TertiaryInd') ,[TertiaryInd] )
)B(Item,Value)
) src
Pivot (max(Value) for Item in (
[BoatPrimaryInd],
[BoatSecondaryInd],
[BoatTertiaryInd],
[AutoPrimaryInd],
[AutoSecondaryInd],
[AutoTertiaryInd],
[HomePrimaryInd],
[HomeSecondaryInd],
[HomeTertiaryInd]
) ) pvt
返回