Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Create Column Headers by Month ID

I am trying to extract itemised sales data for the past 12 months and build a dynamic table with column headers for each month ID. Extracting the data as below works, however when I get to the point of creating a SUM column for each month ID, I get stuck. I have tried to find similar questions but I’m not sure of the best approach.

Select Item, Qty, format(Transaction Date,'MMM-yy')
from Transactions

Data Extract:

Item Qty Month ID
A123 50 Apr-22
A123 30 May-22
A123 50 Jun-22
A321 50 Apr-22
A999 25 May-22
A321 10 Jun-22

Desired Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Item Apr-22 May-22 Jun-22
A123 50 30 50
A321 50 Null 10
A999 Null 25 Null

Any advice would be greatly appreciated.

>Solution :

This is a typical case of pivot operation, where you

  • first filter every value according to your "Month_ID" value
  • then aggregate on common "Item"
WITH cte AS (
    SELECT Item, Qty, FORMAT(Transaction Date,'MMM-yy') AS Month_ID
    FROM Transactions
)
SELECT Item, 
       MAX(CASE WHEN Month_ID = 'Apr-22' THEN Qty END) AS [Apr-22],
       MAX(CASE WHEN Month_ID = 'May-22' THEN Qty END) AS [May-22],
       MAX(CASE WHEN Month_ID = 'Jun-22' THEN Qty END) AS [Jun-22]
FROM cte
GROUP BY Item

Note: you don’t need the SUM as long as there’s only one value for each couple <"Item", "Month-Year">.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading