gpt4 book ai didi

sql-server-2008 - 简单数据透视示例

转载 作者:行者123 更新时间:2023-12-02 01:15:23 25 4
gpt4 key购买 nike

我需要所有 masterid 的报告,但它可能只有一个连续的。我知道这是一件简单的事情,但我无法正确理解语法。

我附上了数据在 SQL Server 中的存储方式以及我希望的输出方式。

数据:

Data

要求的输出:

Required Output

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')

最佳答案

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;

关于sql-server-2008 - 简单数据透视示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12169016/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com