sql server - Is there a way to dynamically produce SQL Columns in a select query? -
my current sql query takes last 6 months , selects sales, so
sum(case when ci.invoicedate >= '20160501' , ci.invoicedate <= '20160531' cid.quantityordered else 0 end) 'may', sum(case when ci.invoicedate >= '20160601' , ci.invoicedate <= '20160630' cid.quantityordered else 0 end) 'june', sum(case when ci.invoicedate >= '20160701' , ci.invoicedate <= '20160731' cid.quantityordered else 0 end) 'july', sum(case when ci.invoicedate >= '20160801' , ci.invoicedate <= '20160831' cid.quantityordered else 0 end) 'august', sum(case when ci.invoicedate >= '20160901' , ci.invoicedate <= '20160930' cid.quantityordered else 0 end) 'september', sum(case when ci.invoicedate >= '20161001' , ci.invoicedate <= '20161030' cid.quantityordered else 0 end) 'october', however, when run report in december, because have hard coded in month names, won't november sales figures.
ideally form of code dynamically produces select query last 6 months in it.
is possible? there documentation can point me towards learn more dynamic sql?
thanks everyone!
get last 6 months names , build dynamic query using pivot:
declare @months nvarchar(max) = '' ;with cte (select datename(month, dateadd(month, 0, getdate())) mn, 0 v union select datename(month, dateadd(month, v - 1, getdate())) mn, v - 1 cte v > -5 ) select @months = @months + '[' + mn + '], ' cte set @months = substring(@months, 1, len(@months) - 1) declare @q nvarchar(max) set @q = ' select * ( select quantityordered qo , datename(month, invoicedate) mn invoicetable ) s pivot (sum(qo) mn in (' + @months + ') ) p' exec(@q)
Comments
Post a Comment