我在动态查询中遇到问题我希望null
的值转换为零,我发现convert
但我的动态查询中的函数不起作用
SET @DynamicPivotQuery =
'select * from (
select ct.category as [name],
CONVERT(nvarchar(50), DATENAME(m, b.date)
+ '', ''
+ DATENAME(yyyy,b.date))as date
, sum(b.value) as value from bus bu
join bus_category buc on bu.id = buc.business_unit_id
join category ct on ct.id = buc.type_id
join bus_actual b on buc.id = b.bus_category_id
where b.date between '''+ cast (@start as VARCHAR(50))+''' and '''+ cast (@actual as VARCHAR(50))+'''
and bu.name = '''+ cast (@bus as VARCHAR(50))+'''
group by buca.date, ct.category_name
我希望来自sum(b.value)
的{{1}}的值转换为零。怎么做???
已更新
NULL
答案 0 :(得分:2)
DECLARE @SQL NVARCHAR(MAX)
SET @SQL = '
SELECT
ct.category AS [name]
, DATENAME(m, b.[date]) + '' '' + DATENAME(yyyy, b.[date])) AS [date]
, ISNULL(SUM(b.value), 0) AS value
FROM dbo.bus bu
JOIN dbo.bus_category buc ON bu.id = buc.business_unit_id
JOIN dbo.category ct ON ct.id = buc.[type_id]
JOIN dbo.bus_actual b ON buc.id = b.bus_category_id
WHERE b.date between @start AND @actual
AND bu.name = @bus
GROUP BY DATENAME(m, b.[date]) + '' '' + DATENAME(yyyy, b.[date])), ct.category'
--PRINT @SQL
EXEC sys.sp_executesql
@SQL,
N'@start VARCHAR(50), @actual VARCHAR(50), @bus VARCHAR(50)',
@start = @start, @actual = @actual, @bus = @bus
更新 -
DECLARE
@DynamicPivotQuery NVARCHAR(MAX)
, @ColumnName NVARCHAR(MAX)
, @start DATETIME
, @end DATETIME
, @actual DATETIME
, @first DATETIME
, @bus VARCHAR(50)
SELECT
@start = '2015-07-01'
, @end = '2016-06-01'
, @actual = '2015-09-01'
, @first = '2015-10-01'
, @bus = 'EUR'
SELECT @ColumnName = STUFF((
SELECT ', ' + QUOTENAME(dt) dt
FROM (
SELECT [date], dt = DATENAME(m, [date]) + ' ' + DATENAME(yyyy, [date])
FROM dbo.bus_actual
WHERE [date] BETWEEN @start AND @actual
UNION
SELECT [date], DATENAME(m, [date]) + ' ' + DATENAME(yyyy, [date])
FROM dbo.bus_forecast
WHERE [date] BETWEEN @first AND @end
) t
ORDER BY [date]
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
SET @DynamicPivotQuery =
'
SELECT *
FROM (
SELECT
ct.category
, [date] = DATENAME(m, bu.[date]) + '' '' + DATENAME(yyyy, bu.[date]))
, bu.value
FROM dbo.bus bu
JOIN dbo.bus_category buc on bu.id = buc.bus_id
JOIN dbo.category ct on ct.id = buc.id
JOIN dbo.bus_actual b on buc.id = b.bus_id
WHERE b.[date] between @startFY and @actual_date
and bu.name = @bus
GROUP BY bu.[date], ct.category
) t
PIVOT(
SUM(value)
FOR [date] IN (' + @ColumnName + ')
) p'
EXEC sys.sp_executesql
@DynamicPivotQuery,
N'@startFY DATETIME, @actual_date DATETIME, @bus VARCHAR(50)',
@startFY = @start, @actual_date = @actual, @bus = @bus
答案 1 :(得分:1)
我猜你需要这样的东西:
IsNull( sum(b.value), 0 )