2016-12-26 16 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代表的值。 –