gpt4 book ai didi

sql - 如何从 sql 数据透视表中删除空值?

转载 作者:行者123 更新时间:2023-12-02 03:32:53 25 4
gpt4 key购买 nike

如何将 SQL 数据透视表中的空值替换为零?

    DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[Offer_cover])
FROM #cover2 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')


set @query = 'SELECT Ref,role_name,offer_id, ' + @cols + ' from
(
select*
from #cover2
) x
pivot
(
SUM(cover_earning_Count)
for [offer_cover] in (' + @cols + ')
) p '
execute(@query)

输出:

Ref         role_name    offer_id   10000   104000  112000
43132_43282 Call Center 1 1 NULL NULL
43132_43282 Others 1 2 NULL NULL
43160_43282 Call Center 1 6 NULL 1
43160_43282 Others 1 NULL 1 NULL
43191_43282 Call Center 1 7 NULL NULL
43191_43282 Others 1 3 1 1
43221_43282 Call Center 1 4 1 1
43221_43282 Others 1 2 NULL NULL

封面2表

Ref YEAR    MONTH   Role_name   offer_cover offer_id    Cover_Earning_Count CONF_DATE   Curr_date
43132_43282 2018 2 Call Center 2000 1 5 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 4000 1 8 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 6000 1 2 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 8000 1 4 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 10000 1 1 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 12000 1 6 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 14000 1 2 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 16000 1 4 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 20000 1 6 2/1/2018 7/1/2018
43132_43282 2018 2 Call Center 24000 1 5 2/1/2018 7/1/2018

最佳答案

正如我之前在评论中提到的,您需要 2 个 @col,一个用于选择,另一个用于数据透视

 DECLARE @cols   AS NVARCHAR(MAX),   -- for pivot
@cols2 AS NVARCHAR(MAX), -- for select
@query AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[Offer_cover])
FROM #cover2 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

-- this is for the SELECT
SET @cols2 = STUFF((SELECT distinct ',' + 'ISNULL(' + QUOTENAME(c.[Offer_cover]) + ', 0) ' + QUOTENAME(c.[Offer_cover])
FROM #cover2 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

set @query = 'SELECT Ref,role_name,offer_id, ' + @cols2 + ' from
(
select *
from #cover2
) x
pivot
(
SUM(cover_earning_Count)
for [Offer_cover] in (' + @cols + ')
) p'

-- do a print to verify the query
print @query

关于sql - 如何从 sql 数据透视表中删除空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51278149/

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