I have a problem in my dynamic query I want that the values that are null
to convert in zero, I found the function that convert
but in my dynamic query does not work
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
I want that values from sum(b.value)
that are NULL
to convert in zero. How to do this???
UPDATED
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @start AS DateTime
DECLARE @end AS DateTime
DECLARE @actual AS DateTime
DECLARE @first AS DateTime
DECLARE @bus AS VARCHAR(50)
SET @start = '2015-07-01';
SET @end = '2016-06-01';
SET @actual = '2015-09-01';
SET @first = '2015-10-01';
SET @bus = 'EUR';
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+ QUOTENAME(date1)
FROM (
SELECT m.date1, m.date2 FROM(
SELECT DISTINCT CONVERT(nvarchar(50), DATENAME(m, date)
+ ', '
+ DATENAME(yyyy,date)) as date1, date as date2
FROM bus_actual where date between @start and @actual
union all
SELECT DISTINCT
CONVERT(nvarchar(50), DATENAME(m, date)
+ ', '
+ DATENAME(yyyy,date)) as date1, date as date3
FROM bus_forecast where date between @first and @end
)m
)tab order by tab.date2
SET @DynamicPivotQuery =
'select * from (
select ct.category as [name],
CONVERT(nvarchar(50), DATENAME(m, bu.date)
+ '', ''
+ DATENAME(yyyy,bu.date))as date
,ISNULL(sum(bu.value),0) as value from bus bu
join bus_category buc on bu.id = buc.bus_id
join category ct on ct.id = buc.id
join bus_actual b on buc.id = b.bus_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 bu.date, ct.category
) as t
PIVOT( SUM(t.value)
FOR date IN (' + @ColumnName + ')) AS PVTTable'
EXEC sp_executesql @DynamicPivotQuery,
N'@start datetime, @actual_date datetime, @bus VARCHAR(50)',
@startFY = @start, @actual = @actual, @bus = @business_unit