簡體   English   中英

SQL - 求和聚合子查詢

[英]SQL - Summing aggregate sub query

這是我的代碼

select  distinct sli.order_no,
            sli.pkg_no,
            case when line.primary_ind = 'Y' then sum(paid_amt) else 0 end  as paid_amt,
            line.pkg_li_no,     
            sum(case when sli.perf_no = 0 then 1 else 0 end) as num_seats_pur,
            sli.status
    from    t_sub_line sli
    left outer join t_line line on sli.li_seq_no = line.li_seq_no
    where sli.order_no in (1,2)
    group by
            sli.order_no,
            sli.pkg_no,
            line.primary_ind,
            line.pkg_li_no,
            sli.status  
    having  line.primary_ind = 'Y'

此代碼生成此 output

order_no pkg_no paid_amt    pkg_li_no   num_seats_pur   status
1        322    124.00      967          2              7
1        322    -124.00     992          2              4
2        854    253.00      952          1              7
2        854    -253.00     996          1              4

我真正需要的數據返回如下。 我需要paid_amt 字段的總和。

order_no pkg_no paid_amt    pkg_li_no   num_seats_pur   status
1        322    0       967              2              7
2        854    0       996              1              4

即使我將狀態更改為最大(狀態),所以它不會對其進行分組。 我沒有 sum_paid amt。

當我嘗試這段代碼時:

sum(case when line.primary_ind = 'Y' then sum(paid_amt) else 0 end)  as paid_amt,

我收到以下錯誤消息

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

你需要做幾件事。

  1. 從 select 中注釋掉 pkg_li_no 並分組
  2. 將 have 語句更改為包含在 where 語句中
  3. 從paid_amt 中刪除案例,因為沒有必要
 select distinct sli.order_no, sli.pkg_no, sum(paid_amt)as paid_amt, -- line.pkg_li_no, sum(case when sli.perf_no = 0 then 1 else 0 end) as num_seats_pur, sli.status from t_sub_line sli left join t_line line on sli.li_seq_no = line.li_seq_no where sli.order_no in (1,2) and line.primary_ind = 'Y' group by sli.order_no, sli.pkg_no, line.primary_ind, -- line.pkg_li_no, sli.status

其他注意事項:我不確定您是否想要 select 或按 pkg_no 或狀態分組,但您更了解正在尋找什么結果。 如果它們是不同的值,就會有不同的記錄。

我不確定您要完成什么,但您似乎對查詢進行了過度思考。 嘗試簡化它。 FYI HAVING發生在分組之后, WHERE發生在分組之前,你甚至不需要CASE

select  distinct sli.order_no,
            sli.pkg_no,
            sum(paid_amt) as paid_amt, 
            sum(case when sli.perf_no = 0 then 1 else 0 end) as num_seats_pur,
            sli.status
    from    t_sub_line sli
    left outer join t_line line on sli.li_seq_no = line.li_seq_no
    where sli.order_no in (1,2)
      and line.primary_ind = 'Y'
    group by
            sli.order_no,
            sli.pkg_no,
            sli.status  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM