添加参数以选择案例db2

时间:2016-12-26 22:15:11

标签: sql db2

我有以下select语句:

 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(*) as num                             
         from INFO                                          
       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   
---------+---------+-----
18-29              828   
30-49             2510   
50-69             2014   
70-100             649   

现在我想添加一个含有男性/女性参数百分比的列&#34; GENDER&#34; (0或1)在&#34; INFO&#34;并使用另一个表&#34; PAYTB&#34;的参数,所有交易的总和&#34; ACAUREQ_AUREQ_TX_DT_TTLAMT&#34;。两个表共享CONT_ID。 它应该是这样的:

 AGE_RANGE          NUM      GENDER       Transaction amount average
---------+---------+---------------------------------------------------
18-29              828        50%         2000 $
30-49             2510        ??          ??? 
50-69             2014        ??          ???
70-100             649  

1 个答案:

答案 0 :(得分:0)

我觉得这样的事情应该适合你。基本上你只是添加了更多的聚合。我改变了你的计数,因为我假设新表和客户表之间存在1到多的关系。

 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 <PK_CLIENT_INFO>) as num ,
             SUM(CASE WHEN CLIENT_INFO = 'MALE' THEN 1 ELSE 0 END) / COUNT(DISTINCT <PK_CLIENT_INFO>) 'Male/Female'
             ,SUM(ACAUREQ_AUREQ_TX_DT_TTLAMT) / COUNT(*) 'TOTAL-Amount Avg'
         from INFO c
         left 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);