Skip to content
Advertisement

SQL Query to group by month and display individual month sum for a record

I’m trying to sum product codes with a particular description as total products sold in a month over the years.

enter image description here

The two table used are:

The date format is in ‘DD-MON-YYYY HH12:MI PM’.

So far I’m able to formulate this:

How do I separate the count as different month columns and get the sum of count in a separate column?

Advertisement

Answer

I would just use conditional aggregation:

Note that for the ordering, prod_code needs to be in the group by — or you need to use an aggregation function such as order by min(d.prod_code).

If you want a separate row for totals, then use grouping sets:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement