按类别和按月/年分组的SQL总和

时间:2016-08-29 20:48:18

标签: sql sql-server group-by categories

尝试按类型对产品总产量求和,并按月/年汇总。

三张桌子:

  • 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

以下脚本有效,但每月为每个类别分别创建一行。我想要一行总共每个产品。我错过了什么?

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

1 个答案:

答案 0 :(得分:1)

尝试在

组中仅使用年份和月份
Group BY  YEAR(OL.batch_date_stop), MONTH(OL.batch_date_stop)