0

我有以下代码:

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

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(month)                   
               from PRCombinedRM    
               group by month,AccountNumber 
        FOR XML PATH(''), TYPE      
        ).value('.', 'NVARCHAR(MAX)')       
    ,1,1,'')            

set @query = 'SELECT AccountNumber,' + 'FullName,' + 'AccountType,' + 'Company,' + 'AccountBalance,' + @cols + ' from                   
         (      
            select AccountNumber,   
                   FullName,
                   AccountType,
                   Company,
                   AccountBalance,
                   month,
                   amount
                from PRCombinedRM
            ) x 
            pivot   
            (   
                sum(amount)
                for month in (' + @cols + ')
            ) p '   

execute(@query)                 

然而,目前输出的结果将“数量”的值显示为 NULL,但是我想用“0”替换 NULL 值。我该怎么做呢?

目前数据输出如下:

AccountNumber   FullName    AccountType Company AccountBalance  Aug     Jul     Jun     Sep 
100 M R Test    Test Account    Test Company    100 -50 -50 NULL    -50

但是我希望数据输出为:

AccountNumber   FullName    AccountType Company AccountBalance  Aug     Jul     Jun     Sep 
100 M R Test    Test Account    Test Company    100 -50 -50 0   -50

谢谢你。

4

2 回答 2

2

我会使用另一个变量来存储ISNULL(someColumn,0)

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

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(month)                   
               from PRCombinedRM    
               group by month,AccountNumber 
        FOR XML PATH(''), TYPE      
        ).value('.', 'NVARCHAR(MAX)')       
    ,1,1,'');

SET @cols2 = STUFF((SELECT distinct ', ISNULL(' + QUOTENAME(month) + ',0) ' + QUOTENAME(month)
               from PRCombinedRM    
               group by month,AccountNumber 
        FOR XML PATH(''), TYPE      
        ).value('.', 'NVARCHAR(MAX)')       
    ,1,1,'');

set @query = 'SELECT AccountNumber,' + 'FullName,' + 'AccountType,' + 'Company,' + 'AccountBalance,' + @cols2 + ' from                   
         (      
            select AccountNumber,   
                   FullName,
                   AccountType,
                   Company,
                   AccountBalance,
                   month,
                   Amount
                from PRCombinedRM
            ) x 
            pivot   
            (   
                sum(amount)
                for month in (' + @cols + ')
            ) p ';

execute(@query);   
于 2016-09-20T14:04:48.657 回答
0

您可以更改@cols定义:

SET @cols = STUFF((SELECT distinct ', coalesce(' + QUOTENAME(month) ', 0) as ' + QUOTENAME(month)                 
               from PRCombinedRM    
               group by month,AccountNumber 
        FOR XML PATH(''), TYPE      
        ).value('.', 'NVARCHAR(MAX)')       
    , 1, 2,'')            
于 2016-09-20T14:02:54.723 回答