没有Null值的动态Pivot

时间:2015-09-26 09:21:22

标签: pivot

这是Northwind数据库中的动态交叉表查询:

DECLARE @COUNTRY NVARCHAR(MAX) ='', @COUNTRY2 NVARCHAR(MAX)

SELECT @COUNTRY = @COUNTRY + QUOTENAME(Country)+', '
FROM Customers
GROUP BY Country

SET @COUNTRY= LEFT(@COUNTRY, LEN(@COUNTRY)-1)

SET @COUNTRY2 = REPLACE(@COUNTRY, ',' , '+')

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = 'SELECT * , '+@COUNTRY2+' AS TOTAL
           FROM (SELECT E.EmployeeID, E.LastName, 
                        ISNULL( OD.Quantity, 0)* ISNULL(OD.[UnitPrice],0) QU,
                        O.ShipCountry AS CO
                 FROM Orders O JOIN Employees E ON O.EmployeeID = E.EmployeeID
                      JOIN [dbo].[Order Details] OD ON OD.OrderID = O.OrderID) AS T
PIVOT(SUM(QU) FOR CO IN ('+@COUNTRY+')) AS PVT
ORDER BY 1'
EXEC(@SQL) 

我需要以Null值替换为0的方式更改代码。

Result of the Query:

2 个答案:

答案 0 :(得分:1)

DECLARE @COUNTRY NVARCHAR(MAX) = '' ,
  @COUNTRY2 NVARCHAR(MAX);

SELECT  @COUNTRY = @COUNTRY + COALESCE(QUOTENAME(Country) + ', ', '')
FROM    Customers
WHERE   EXISTS ( SELECT *
                 FROM   [Orders] AS [o]
                 WHERE  o.[CustomerID] = Customers.[CustomerID] )
GROUP BY Country;

SET @COUNTRY = LEFT(@COUNTRY, LEN(@COUNTRY) - 1);

SET @COUNTRY2 = REPLACE(@COUNTRY, ',', '+');

DECLARE @SQL NVARCHAR(MAX);

SET @SQL = 'SELECT * , ' + @COUNTRY2 +
  ' AS TOTAL
           FROM (
           SELECT  oe.EmployeeID, oe.LastName, oe.ShipCountry AS CO,
        COALESCE(OD.Quantity * OD.UnitPrice, 0) AS QU
FROM    (
          SELECT  EmployeeID, LastName, ShipCountry
          FROM    (
                    SELECT DISTINCT
                            ShipCountry
                    FROM    Orders
                  ) o ,
                  Employees
        ) oe
LEFT JOIN Orders O ON O.EmployeeID = oe.EmployeeID AND
                  [oe].[ShipCountry] = [O].[ShipCountry]
LEFT JOIN [Order Details] OD ON OD.OrderID = O.OrderID 
           ) AS T
PIVOT(SUM(QU) FOR CO IN (' + @COUNTRY + ')) AS PVT
ORDER BY 1';

EXEC(@SQL); 

答案 1 :(得分:-1)

您需要将SELECT *更改为:

SELECT ISNULL(Argentina,0) AS 'Argentina' , INSNULL(Belgium,0) AS 'Belgium' , ....

当然,您需要更改动态查询以反映ISNULL函数。

祝你好运