SQL Server:用动态PIVOT替换null值

时间:2013-12-23 04:15:44

标签: sql sql-server pivot isnull

我的查询是

DECLARE @cols VARCHAR(MAX),@sql varchar(max)

SET @cols = STUFF(
   (SELECT N',' + QUOTENAME(w) AS [text()]
    FROM (SELECT DISTINCT voucherName AS W 
          FROM tbl_Acc_Voucher 
          WHERE voucherType = 'Sales Invoice') AS W
    ORDER BY W
    FOR XML PATH('')), 1, 1, N'');

SET @sql = 'SELECT * FROM (
    SELECT voucherName,taxAmount FROM tbl_Acc_SalesMaster AS SM
    INNER JOIN tbl_Acc_Voucher AS V ON SM.voucherTypeId = V.voucherId  
    WHERE SM.invoiceNo=  ''' + @invoiceNo + ''' ) AS I
    PIVOT(SUM(taxAmount) FOR voucherName IN (' + @cols + N')) AS PIVOTTED;
    '

EXEC(@sql)

0 个答案:

没有答案