删除重复项和SUM

时间:2014-11-18 14:05:55

标签: sql

    SELECT 

         sku_master.sku
       , sku_master.description
       , sku_master.min_on_hand
       , sku_master.max_on_hand
       , location_inventory.qty_on_hand

  FROM [FCI].[dbo].[location_inventory]
  JOIN [FCI].dbo.[sku_master] ON location_inventory.sku = sku_master.sku
  WHERE min_on_hand > 0
  GROUP BY sku_master.sku

我想要实现的目标是我想将所有重复的SKU组合在一起并将qty_on_hand加起来。我无法弄清楚如何做到这一点。

3 个答案:

答案 0 :(得分:2)

    SELECT 
         sku_master.sku
       , sku_master.description
       , sku_master.min_on_hand
       , sku_master.max_on_hand
       , sum(location_inventory.qty_on_hand)
  FROM [FCI].[dbo].[location_inventory]
  JOIN [FCI].dbo.[sku_master] ON location_inventory.sku = sku_master.sku
  WHERE min_on_hand > 0
  GROUP BY sku_master.sku, 
           sku_master.description, 
           sku_master.min_on_hand,
           sku_master.max_on_hand;

答案 1 :(得分:2)

这将通过SKU获得总数:

SELECT 
     sku_master.sku
   , sum(location_inventory.qty_on_hand) as total_qty_on_hand
FROM [FCI].[dbo].[location_inventory]
JOIN [FCI].dbo.[sku_master] ON location_inventory.sku = sku_master.sku
WHERE min_on_hand > 0
GROUP BY sku_master.sku

如果您还想要其他属性frm SKU_MASTER表,您可以将此结果加入另一个查询:

SELECT 
     sku_master.sku
   , sku_master.description
   , sku_master.min_on_hand
   , sku_master.max_on_hand
   , x.total_qty_on_hand
FROM [FCI].dbo.[sku_master]
inner join
(
  SELECT 
     sku_master.sku
   , sum(location_inventory.qty_on_hand) as total_qty_on_hand
  FROM [FCI].[dbo].[location_inventory]
  JOIN [FCI].dbo.[sku_master] ON location_inventory.sku = sku_master.sku
  WHERE min_on_hand > 0
  GROUP BY sku_master.sku
) x on sku_master.sku = x.sku

答案 2 :(得分:1)

SELECT sku_master.sku
, SUM(location_inventory.qty_on_hand)
FROM [FCI].[dbo].[location_inventory]
JOIN [FCI].dbo.[sku_master] ON location_inventory.sku = sku_master.sku
WHERE sku_master.min_on_hand > 0
GROUP BY sku_master.sku
相关问题