Postgres聚合条件总和

时间:2014-06-04 06:41:14

标签: sql postgresql-9.1

我正在尝试总结 - 汇总条件产品的总重量(我希望这是有道理的)。我收到错误:

  

错误:聚合函数调用无法嵌套   第6行:,SUM(例如,当pc.type =' TEES'那么(SUM(opd.qt ...

这是查询摘录:

SELECT DISTINCT
         o.work_order_number dn
       , SUM(opd.qty) units
       , SUM (CASE  WHEN pc.type = 'TEES' THEN (SUM (opd.qty) * .75)
            WHEN pc.type = 'JERSEYS' THEN (SUM (opd.qty) * 1.5)
        END) AS weight

2 个答案:

答案 0 :(得分:13)

尝试:

SELECT o.work_order_number dn 
     , SUM(opd.qty) units 
     , SUM ( opd.qty * CASE pc.type 
                           WHEN 'TEES' THEN 0.75 
                           WHEN 'JERSEYS' THEN 1.5 
                       END ) AS weight
FROM ...
GROUP BY o.work_order_number

答案 1 :(得分:0)

你可以做的就是嵌套你的选择语句E.g

select sum(weight),sum(etc) 
from (
    SELECT DISTINCT o.work_order_number dn 
                 , (opd.qty) units 
                 , ( CASE WHEN pc.type = 'TEES' THEN ((opd.qty) * .75) 
                          WHEN pc.type = 'JERSEYS' THEN ((opd.qty) * 1.5) END) AS weight)
).

因此,第一个选择语句包含你的case语句,第二个选择语句总结你的字段。