My Current sql query takes the last 6 months and selects the sales, like so
SUM(CASE WHEN ci.InvoiceDate >= '20160501' AND ci.InvoiceDate <= '20160531' THEN cid.QuantityOrdered ELSE 0 END) AS 'May',
SUM(CASE WHEN ci.InvoiceDate >= '20160601' AND ci.InvoiceDate <= '20160630' THEN cid.QuantityOrdered ELSE 0 END) AS 'June',
SUM(CASE WHEN ci.InvoiceDate >= '20160701' AND ci.InvoiceDate <= '20160731' THEN cid.QuantityOrdered ELSE 0 END) AS 'July',
SUM(CASE WHEN ci.InvoiceDate >= '20160801' AND ci.InvoiceDate <= '20160831' THEN cid.QuantityOrdered ELSE 0 END) AS 'August',
SUM(CASE WHEN ci.InvoiceDate >= '20160901' AND ci.InvoiceDate <= '20160930' THEN cid.QuantityOrdered ELSE 0 END) AS 'September',
SUM(CASE WHEN ci.InvoiceDate >= '20161001' AND ci.InvoiceDate <= '20161030' THEN cid.QuantityOrdered ELSE 0 END) AS 'October',
However, when I run this report in December, because I have hard coded in the Month names, I won't get the November sales figures.
Ideally I would like some form of code that dynamically produces select query with the last 6 months in it.
Is this even possible? Is there any documentation someone can point me towards to learn more about dynamic SQL?
Thanks everyone!