2016-12-26 17 views
0

我有以下的select语句:添加参数选择的情况下DB2

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 

现在我想用/男性的女性所占百分比参数“性别”添加一列(0或者1)在“INFO”中,并且与另一个表“PAYTB”的参数相加,即所有事务“ACAUREQ_AUREQ_TX_DT_TTLAMT”的总和。两个表共享CONT_ID。 它应该是这样的:

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

回答

0

我觉得这样的事情应该为你做它。基本上你只是添加更多的总量。我更改了Counts,因为我认为新表和客户表之间存在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); 
+0

我有此线 CASE WHEN问题性别= '1' THEN ELSE 1 0 END/COUNT(DISTINCT c.CONT_ID) '男/女' – bastel

+0

@bastel比较遗憾的是,它应当由包围SUM(),因此它为每个男性或每个女性添加1,具体取决于1代表的值。 –