【问题标题】:Replace null values with 0 in PIVOT在 PIVOT 中用 0 替换空值
【发布时间】:2020-06-02 09:53:40
【问题描述】:

我尝试在 PIVOT 函数中将(空)值转换为 0(零)输出,但没有成功。

下面是我尝试过的表格和语法:

SELECT DISTINCT isnull([DayLoad],0) FROM #Temp1

表格#Temp1中的数据:

zone  dayB    templt cid  DayLoad
other 10      other   1    2020-05-28
other 10      other   1    2020-05-29
other 10      other   1    2020-05-30
other 10      other   1    2020-05-31
other 4       other   1    2020-06-02
other 10      other   1    2020-06-02
other 10      other   1    2020-06-01

我的要求:

DECLARE @cols NVARCHAR (MAX)
SELECT @cols = COALESCE (@cols + ',[' + CONVERT(NVARCHAR, [DayLoad], 106) + ']', 
                                  '[' + CONVERT(NVARCHAR, [DayLoad], 106) + ']')
               FROM    (SELECT DISTINCT [DayLoad] FROM #Temp1) PV  
               ORDER BY [DayLoad]

DECLARE @query NVARCHAR(MAX)
SET @query = '           
              SELECT *
                      into #temptable
                      FROM 
             (
                 SELECT 

                ''''+[zone]+'' ''          + ''''+convert(varchar(50),[dayB])+''''+''+''           +'' ''+(case when [templt]=''Прочее'' then '''' else [templt] end)+''''    as [zone/dayB]
                ,[DayLoad]
                ,[cid]
                ,[dayB]
                ,[zone]
                FROM #Temp1
             ) x
             PIVOT 
             (
                 sum([cid])  
                 FOR [DayLoad] IN ('+ @cols + ')
            ) p 

select *
from #temptable            
order by [zone],[dayB]

drop table #temptable      
            '     
EXEC(@query)
DROP TABLE #Temp1

【问题讨论】:

    标签: sql sql-server pivot isnull


    【解决方案1】:

    请参考下面的例子,当你有 null 和空字符串时,正确的选择是使用 case 语句,

    SELECT DISTINCT case when ([DayLoad] is null or [DayLoad] = '') then 0 else [DayLoad] end FROM #Temp1
    

    【讨论】:

      猜你喜欢
      • 2013-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      相关资源
      最近更新 更多