gpt4 book ai didi

sql - SQL Server 数据透视表中为空?

转载 作者:行者123 更新时间:2023-12-03 01:36:03 26 4
gpt4 key购买 nike

我有这个查询

DECLARE @Test TABLE
(
RowID INT IDENTITY(1,1) PRIMARY KEY
,[Name]VARCHAR(10) NOT NULL
,tool VARCHAR(10) NOT NULL,
stam NVARCHAR(MAX)

);
INSERT @Test VALUES ('john', 'vocals','1');
INSERT @Test VALUES ('john', 'guitar','1');
INSERT @Test VALUES ('paul', 'vocals','1');
INSERT @Test VALUES ('paul', 'bass','1');
INSERT @Test VALUES ('george', 'vocals','1');
INSERT @Test VALUES ('george', 1,'1');
INSERT @Test VALUES ('ringo', 'vocals','1');
INSERT @Test VALUES ('ringo', 3,'1');
INSERT @Test VALUES ('ringo', 'drums','1');
INSERT @Test VALUES ('yoko', 'vocals','1');
INSERT @Test VALUES ('royi', 'vocals','1');
INSERT @Test VALUES ('royi', 'guitar','1');


;WITH PivotSource
AS
(
SELECT t.[Name], t.[tool]
FROM @Test t
)

SELECT *
FROM PivotSource
PIVOT ( max(tool) FOR tool IN ([vocals], [guitar], [bass],[drums]) ) pvt;

结果是:

enter image description here

有没有办法将 null 替换为 "" (空字符串)? (无需修改 CTE 数据!)

最佳答案

用途:

SELECT pvt.Name
, isnull(pvt.[vocals], '') [vocals]
, isnull(pvt.[guitar], '') [guitar]
, isnull(pvt.[bass], '') [bass]
, isnull(pvt.[drums], '') [drums]
FROM PivotSource
PIVOT
(
max(tool)
FOR tool
IN ([vocals], [guitar], [bass], [drums])
) pvt;

输出:

Name       vocals     guitar     bass       drums
---------- ---------- ---------- ---------- ----------
george vocals
john vocals guitar
paul vocals bass
ringo vocals drums
royi vocals guitar
yoko vocals

关于sql - SQL Server 数据透视表中为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9567807/

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