2011-11-05 54 views
0

我試圖做一些數據分析,年齡和需要做一個有條件的總和,即我的表是:MySQL的條件求和

ID | Date | Amount | 
===+=========+========+  
1 | 1/1/10 | 100 | 
2 | 1/2/10 | 100 | 
3 | 1/5/10 | 100 | 
4 | 15/5/10 | 100 | 
5 | 20/5/10 | 100 | 

說今天的日期是10年1月6日,我想根據年齡分析中使用的年齡對數量進行求和。即我想這一點

Age  | Total 
===========+====== 
<30 days | 300 
30-60 days | 0 
60-90 days | 0 
90 days+ | 200 

本質上它是一種有條件的總和,所以我想(60-90天,然後90天+ < 30天,然後30-60天,然後)

+0

有類似的東西你想要做的[這裏]什麼(http://stackoverflow.com/questions/4278570/get-sum-of-sales-for-multiple-years -in-列)。 – Bojangles

+0

非常感謝您的幫助 – Akshat

回答

2
總結所有的值

你可以這樣做:

select case 
      when datediff(now(), date) >= 90 then '90 days+' 
      when datediff(now(), date) >= 60 and datediff(now(), date) < 90 then '60-90 days' 
      when datediff(now(), date) >= 30 and datediff(now(), date) < 60 then '30-60 days' 
      else '< 30 days' 
     end case f, 
     sum(amount) 
    from your_table 
group by f; 
+0

這真是太棒了! – Akshat