sheehan46 sheehan46 - 3 months ago 8
SQL Question

SQL Sum by Category and group by month/year

Attempting to sum the total product manufactured by type and summarized by month/year.

Three tables:


  • Order_Line: id, batch_date_stop, item_id

  • Order_Line_Detail: order_line_id, batched_qty, item_id

  • Mill_Item_Map: item_id, item_class



The below script works but is making a separate line for each category each month. I would like one line with a total of each product. What am I missing?

SELECT
YEAR(OL.batch_date_stop) as [Manf Year],
MONTH(OL.batch_date_stop) as [Manf Month],
SUM(case when MIM.item_class is not null then OLD.batched_qty else 0 end)/2000 AS Total,
SUM(case when MIM.item_class = 'CAKE' then OLD.batched_qty else 0 end)/2000 AS [Cake],
SUM(case when MIM.item_class = 'PELLET' then OLD.batched_qty end)/2000 AS [Pellet],
SUM(case when MIM.item_class = 'MINERAL' then OLD.batched_qty end)/2000 AS [Mineral],
SUM(case when MIM.item_class = 'MIX' then OLD.batched_qty end)/2000 AS [Mix],
SUM(case when MIM.item_class = 'GRAIN' then OLD.batched_qty end)/2000 AS [Grain]
FROM Order_Line OL
JOIN order_line_detail OLD ON OLD.order_line_id = OL.id
JOIN mill_item_map MIM ON MIM.item_id = OL.item_id
WHERE YEAR(OL.batch_date_stop) = 2016 and
OLD.sequence_number = 0
Group BY MIM.item_class, YEAR(OL.batch_date_stop), MONTH(OL.batch_date_stop)
ORDER BY YEAR(OL.batch_date_stop), MONTH(OL.batch_date_stop)


enter image description here

Answer

Try using only year and month in group by

Group BY  YEAR(OL.batch_date_stop), MONTH(OL.batch_date_stop)
Comments