从多个表中选择顶级产品组合重复产品和SUM数量

时间:2016-10-04 11:26:32

标签: sql postgresql

我有多个销售清单表我想选择每个表的最高产品(数量值较高)和"验证仅在主表中销售"从每个销售清单表中选择所有表的顶级产品。 这就是我到目前为止所做的:

  SELECT code_p, SUM(total) 
  FROM (   
  SELECT code_p as code_p, SUM(qty_p) as total from table1_sells_list d 
  INNER JOIN table1 p ON d.code_t1 = p.code_t1 
  WHERE valid_t3 = true 
  GROUP BY code_p, qty_p
-----------------------------------------------------------------------
  UNION ALL 
  SELECT code_p, SUM(qty_p) as total from table2_sells_list a
  INNER JOIN table2 c ON a.code_t2 = c.code_t2 
  WHERE valider_t3 = true 
  GROUP BY code_p, qty_p
-----------------------------------------------------------------------
  UNION ALL 
  SELECT code_p, SUM(qty_p) as total from table2_sells_list e
  INNER JOIN table3 f ON e.code_t3 = f.code_t3 
  WHERE valider_t3 = true 
  GROUP BY code_p, qty_p
      ) a 
  GROUP BY code_p, total
  ORDER BY code_p, total DESC

结果如下:

enter image description here

正如您所看到的那样,有两行具有相同的产品,我想要做的是将重复的行和SUM相加,如下所示:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将整个查询包装在

SELECT code_p, sum(sum)
FROM ( <your original query> ) x
GROUP BY code_p;