Dear Experts,
I have the below dynamic pivot query for customer ageing
Declare @fromdate as datetime
Declare @Todate as datetime
set @fromdate = /* select min(Ta.[fromDate]) from osrt ta where Ta.[fromDate] >= */ [%0]
set @Todate = /* select max(Tb.[toDate]) from osrt tb where Tb.[toDate] <= */ [%1]
declare @cols nvarchar (max)= N''
declare @A nvarchar (max)
select @cols = @cols + case when @cols = N'' then QUOTENAME((month([TAXDATE]))) else N',' + QUOTENAME((month([TAXDATE]) )) end
from JDT1
group by month([TAXDATE])
order by month([TAXDATE]) DESC
set @A = 'select * from (select month(T0.[TAXDATE]) as date,T1.[CardName] as name, T1.[Balance] as balance,YEAR(T0.[TAXDATE]) AS YEAR, ( T0.[BalDueDeb]-T0.[BalDueCred]) as total FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.[ShortName] = T1.CardCode WHERE T0.[TaxDate] between @fromdate and @todate and T1.[CardType]= ''c'' and ( T0.[BalDueDeb]-T0.[BalDueCred])<>0)s
pivot
(sum (Total) for date in (' + @cols +'))p ORDER BY NAME,YEAR'
exec sp_executesql @A , N'@FROMDATE date, @TODATE date', @FROMDATE = @FROMDATE, @TODATE =@TODATE
The query works fine. But I would like to concat the month and year. I have tried using concat,
concat(month([taxdate]),'-',year([taxdate])
but it gives me error
1). 'CONCAT' is not a recognized built-in function name. (SWEI) (s) could not be prepared.
I have also tried using
month([taxdate]) + '' + year([taxdate])
but even that too also gives an error
1). The column '2019' was specified multiple times for 'p'. 'User-Defined Values' (CSHS)
What am I doing wrong?
Furthermore,
a) I have noticed that the above query also displays columns that are out of range of the date parameters. For these out of range from the date parameters, the columns are displayed as blanks. How to exclude these out of range of date parameters columns?
b) Another thing is that even within the date range parameters, columns that are blank are also shown. How to ensure that it does not show blank columns?
Is it even possible to resolve (a) and (b)? If not possible, then that is OK. My main problem is to be able to concat the month and year.
Any help in resolving the above will be appreciated.
Thanking you,
With regards
MK Shah