首页 > 解决方案 > 在 SQL Server 2008 的 PIVOT 查询中使用 ISNULL

问题描述

我正在使用 SQL Pivot 列出每种产品每天的销售额总价值,但在替换行的 NULL 值时遇到了麻烦。

下表是我的数据示例

    Date    | Product |  Amount  | Price  |
------------+---------+----------+--------+
2018-01-06  |  PRO 1  |    2     |   5    |
2018-01-06  |  PRO 2  |    3     |   6    |
2018-01-06  |  PRO 2  |    1     |   6    |
2018-01-06  |  PRO 3  |    4     |   18   |
2018-01-06  |  PRO 4  |    2     |   5    |
2018-01-06  |  PRO 5  |    3     |   6    |
2018-01-06  |  PRO 6  |    2     |   3    |
2018-01-06  |  PRO 6  |    7     |   3    |
2018-01-07  |  PRO 6  |    7     |   3    |

我的查询:

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME([Product]) + ',' FROM (select distinct [Product] from #sales) as tmp
SELECT @cols = substring(@cols, 0, len(@cols)) --trim "," at end

set @query =
'SELECT * from (
    Select [Date], ([Amount]*[Price]) as [TOTAL], [Product] from #Sales group by Date, Product, Amount, Price
) src
pivot
(
    SUM([TOTAL]) for [Product] in (' + @cols + ')
) piv'

execute(@query)

我的结果:

   Date    | PRO 1  | PRO 2  | PRO 3  | PRO 4  | PRO 5  | PRO 6  |
-----------+--------+--------+--------+--------+--------+--------|
2018-01-06 |   10   |   24   |   72   |   10   |   18   |   27   |
2018-01-07 |  NULL  |  NULL  |  NULL  |  NULL  |  NULL  |   21   |

如何用 0 替换 NULL 值?做ISNULL(([Amount]*[Price]),0)似乎并没有为它做任何事情。

标签: sql-servertsql

解决方案


您必须替换*为动态列列表,并ISNULL在那里使用。生成这个列表的代码可能是这样的:

DECLARE @cols2  AS NVARCHAR(MAX)='[Date], ';
SELECT @cols2 = @cols2 + 'ISNULL(' + QUOTENAME([Product]) + ', 0) as ' + QUOTENAME([Product]) + ',' FROM (select distinct [Product] from #sales) as tmp
SELECT @cols2 = substring(@cols2, 0, len(@cols2)) --trim "," at end

推荐阅读