sql-server - 在 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)
似乎并没有为它做任何事情。
解决方案
您必须替换*
为动态列列表,并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
推荐阅读
- java - 在 Spring Boot 中发送 sendgrid 电子邮件的最简单方法
- vba - 使用 VBA 折叠组的更有效方法
- amazon-s3 - 运行 FFmpeg 命令
- liferay - 如何在 Liferay 7 Search 中使用 AND 或 OR 等逻辑运算符?
- r - 通过 Trace() 更改 .R 文件中的代码以在终端中提供正确的输出
- javascript - 如何将字符串“'opt01', 'opt\'02', 'op,t03'” 更改为数组
- javascript - 根据其中一个键的条件从数组中获取单个对象
- c# - 创建 Windows 服务时,是否可以使用新的 .csproj 格式?
- c++ - 将 Xcode 更新到 9.3 时出现链接器错误
- c# - C#获取mysql自动增量值