Есть запрос:
SELECT [ConceptionName], [mainRoleCode], [UserName], [UnitTabel] as staff,
CAST([DateTime] AS date) AS date
INTO #Test
FROM[Authorization] WHERE DateTime BETWEEN '2019-01-21T00:00:00' AND '2019-01-24T00:00:00'
SELECT [ConceptionName], [mainRoleCode], [UserName], sum(staff) AS [staff], [date]
INTO #TestPivot
FROM #Test
GROUP BY [ConceptionName], [mainRoleCode], [UserName], [date]
SELECT [date]
INTO #TestPivotDate
FROM #Test
GROUP BY [date]
DECLARE @Dates nvarchar(MAX);
SELECT @Dates = stuff((select ',' + '[' + left(convert(nvarchar,[date], 120), 10) + ']' FROM #TestPivotDate ORDER BY [date] FOR xml path('')),1,1,'')
DECLARE @SqlCode nvarchar(MAX);
SELECT @SqlCode = '
SELECT p.*, ' + REPLACE(REPLACE(REPLACE(@Dates, ',', '+'), '[', 'ISNULL(['), ']', '], 0)') + ' AS [Итого]
FROM (
select [ConceptionName],[mainRoleCode],[UserName],' + @Dates + ' FROM #TestPivot pivot(sum([staff]) for [date] in (' + @Dates + ')) AS pvt
) p
ORDER BY p.[ConceptionName]'
EXEC sp_executesql @SqlCode
DROP TABLE #Test,#TestPivot,#TestPivotDate
Он выдает результат
Как сделать чтобы в результате заместо NULL был пробел или 0 ?
при pivot(sum(coalesce([staff],0)) for [date] in (' + @Dates + ')) AS pvt) p
выдает "Неправильный синтаксис около ключевого слова "coalesce"
при pivot(sum(isnull([staff],0)) for [date] in (' + @Dates + ')) AS pvt) p
выдает "Неправильный синтаксис около конструкции "(".
при pivot(isnull(sum([staff]),0) for [date] in (' + @Dates + ')) AS pvt ) p
выдает " isnull не является известным агрегатная функция."
SELECT p.*
распишитеSELECT [ConceptionName],[mainRoleCode],[UserName], ISNULL([2019-01-20], 0) AS [2019-01-20],....
то ли REPLACE-ом, то ли через подготовленную аналогично@Dates
переменную