我需要所有masterid的报告,但它可能只是连续一个..我知道这是一件很简单的事情,但我无法正确理解语法。
我附加了数据如何存储在SQL服务器和输出中的方式。
数据:
必需输出:
CREATE TABLE [dbo].[Services]
([ServiceID] [int] IDENTITY(1,1) NOT NULL,
[MasterID] [nvarchar](10) NOT NULL,
[Type] [nvarchar](50) NOT NULL,
[Status] [nvarchar](50) NOT NULL)
Insert Into Services (MasterID, Type , Status) values (123, 'Basic Phone', 'Open')
Insert Into Services (MasterID, Type , Status) values (123, 'BlackBerry', 'Open')
Insert Into Services (MasterID, Type , Status) values (123, 'Pixi', 'Closed')
答案 0 :(得分:5)
SELECT MasterID,
[Basic Phone] = MAX([Basic Phone]),
[Pixi] = MAX([Pixi]),
[Blackberry] = MAX([Blackberry])
FROM
(
SELECT MasterID, [Basic Phone],[Pixi],[Blackberry]
FROM dbo.Services AS s
PIVOT
(
MAX([Status]) FOR [Type] IN ([Basic Phone],[Blackberry],[Pixi])
) AS p
) AS x
GROUP BY MasterID;
或更简单 - 并归功于@YS。指出我的冗余。
SELECT MasterID,
[Basic Phone],
[Pixi],
[Blackberry]
FROM
(
SELECT MasterID, Status, Type FROM dbo.Services
)
AS s
PIVOT
(
MAX([Status]) FOR [Type] IN ([Basic Phone], [Blackberry], [Pixi])
) AS p;