mysql条件求和

时间:2011-11-05 15:33:27

标签: mysql conditional sum

我正在尝试对某些数据进行年龄分析,需要进行条件求和,即我的表格是:

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    |

说今天的日期是1/6/10我想根据年龄分析中使用的年龄来计算金额。即我喜欢这个

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

基本上它是一个条件求和,所以我想总结所有的值(<30天,然后30-60天,然后60-90天,然后90天+)

1 个答案:

答案 0 :(得分: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;