如何在动态数据透视sql中使用ISNULL?

时间:2017-09-07 20:44:51

标签: sql-server

我有一个像下面这样的表,当我使用动态数据透视表时,一切正常,直到我想要总结所有行。我有一个问题是将NULL更改为0。 查询的哪一部分应该放入ISNULL函数?

表:

klucz      logid_do_zliczenia   duration
556267831171038 1171038 1058
556267831171038 1171038 54
556267831170688 1170688 72
556267831171038 1171038 59
556267831170688 1170688 46
556267831171038 1171038 54
556267831170688 1170688 42
556267831171038 1171038 12
556267831170634 1170634 112
556267831170634 1170634 53
556267831141392 1141392 77
556290551161102 1161102 32
556290551140814 1140814 249
556290551140814 1140814 43
556290551140814 1140814 105
556290551140814 1140814 40
556290551140814 1140814 304
556290551140814 1140814 61
556290551150534 1150534 351
556290551150534 1150534 76
556290551141170 1141170 238

查询:

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);             

SET @Columns = (SELECT  N', p.' + QUOTENAME(REPLACE(CONVERT(VARCHAR(max), p.logid_do_zliczenia, 111), '/', '-'))
                FROM    #3 AS p
                GROUP BY p.logid_do_zliczenia
                ORDER BY p.logid_do_zliczenia
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)');            



SET @sql = N'SELECT klucz, ' + STUFF(@columns, 1, 2, '') + ',

Suma = ' + STUFF(REPLACE(@columns, ', p.[', ' + p.['), 1, 3, '') + '
FROM
(
  SELECT p.logid_do_zliczenia, p.klucz, p.duration FROM #3 AS p
) AS j
PIVOT
(
  SUM(duration) FOR logid_do_zliczenia IN ('+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '') + ')
) AS p;';
EXEC sp_executesql @sql;

如何更改?

1 个答案:

答案 0 :(得分:1)

试试这个

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);             

SET @Columns = (SELECT  N', p.' + QUOTENAME(REPLACE(CONVERT(VARCHAR(max), p.logid_do_zliczenia, 111), '/', '-'))
                FROM    #3 AS p
                GROUP BY p.logid_do_zliczenia
                ORDER BY p.logid_do_zliczenia
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)');            



SET @sql = N'SELECT klucz, ' + STUFF(@columns, 1, 2, '') + ',

Suma = ' + STUFF(REPLACE(@columns, ', p.[', ',0) + ISNULL(p.['), 1, 3, '') + ',0)
FROM
(
  SELECT p.logid_do_zliczenia, p.klucz, p.duration FROM #3 AS p
) AS j
PIVOT
(
  SUM(duration) FOR logid_do_zliczenia IN ('+ STUFF(REPLACE(@columns, ', p.[', ',['), 1, 1, '') + ')
) AS p;';

EXEC sp_executesql @sql;