选择案例陈述添加信息

时间:2016-12-27 12:26:44

标签: sql sum db2

我有2张表cardinfo和paytb。在我的发言中,我通过CONT_ID加入了他们。

 select (case when age_years >= 18 and age_years < 30 then '18-29'
            when age_years < 50 then '30-49'
            when age_years < 70 then '50-69'
             when age_years < 100 then '70-100'
            end) as age_range,
             count(DISTINCT c.CONT_ID) as num,
     CASE WHEN GENDER = '1' THEN 1 ELSE 0 END / COUNT(DISTINCT c.CONT_ID),
     SUM(ACAUREQ_AUREQ_TX_DT_TTLAMT) / COUNT(*) 'TOTAL-Amount Avg' 
         from cardinfo c
         left join paytb t
          on c.CONT_ID = t.CONT_ID
      group by (case when age_years >= 18 and age_years < 30 then '18-29'
         when age_years < 50 then '30-49'
         when age_years < 70 then '50-69'
         when age_years < 100 then '70-100'
         end)
         order by min(age_years);       

现在显示前两列:

 AGE_RANGE          NUM      GENDER      
---------+---------+----------------
18-29              828        50%        
30-49             2510        ??         
50-69             2014        ??         
70-100             649                

我想从表中添加GENDER参数(0或1)。但是这不起作用:

CASE WHEN GENDER = '1' THEN 1 ELSE 0 END / COUNT(DISTINCT c.CONT_ID)  

sqlcode = -122

我试图找到交易的平均值:

SUM(ACAUREQ_AUREQ_TX_DT_TTLAMT) / COUNT(*) 'TOTAL-Amount Avg' 

不幸的是,这会给我一个DECFLOAT错误 总和看起来像这样:

  SUM(ACAUREQ_AUREQ_TX_DT_TTLAMT)
    -----+---------+---------+---------+
    +1.232071426000000000000000E+0007   
    +3.062581021000000000000000E+0007   
    +2.399951792000000000000000E+0007   
    +8.228919170000000000000000E+0006   

2 个答案:

答案 0 :(得分:0)

您需要在gender中包含group by或将其作为聚合函数的参数:

SUM(CASE WHEN GENDER = '1' THEN 1 ELSE 0 END) / COUNT(DISTINCT c.CONT_ID)

但是,您可能不需要COUNT(DISTINCT)。如果没有必要,可以将其简化为:

AVG(CASE WHEN GENDER = '1' THEN 1.0 ELSE 0 END)

答案 1 :(得分:0)

我将原始查询包装在派生表中,以保存一些输入:

select age_range,
       count(DISTINCT CONT_ID) as num,
       CASE WHEN GENDER = '1' THEN 1 ELSE 0 END / COUNT(DISTINCT c.CONT_ID),
       SUM(ACAUREQ_AUREQ_TX_DT_TTLAMT) / COUNT(*) 'TOTAL-Amount Avg' 
from
(
    select (case when age_years >= 18 and age_years < 30 then '18-29'
                 when age_years < 50 then '30-49'
                 when age_years < 70 then '50-69'
                 when age_years < 100 then '70-100'
            end) as age_range,
            c.CONT_ID,
            GENDER,
            ACAUREQ_AUREQ_TX_DT_TTLAMT
    from CARDUSR.CLIENT_INFO c
    left join cardusr.sppaytb t
        on c.CONT_ID = t.CONT_ID
)
group by age_range, GENDER