2011-11-18 40 views
3

我想在一個查詢中執行兩個不同的SUM。MySQL:是否可以使用單個查詢來完成此操作?

user points date_achieved 
----------------------------- 
Foo 10  2000-01-01 
Foo 20  2011-11-18 
Bar 10  2000-01-01 
Bar 20  2011-11-15 
Bar 30  2011-11-18 

1)總分

SELECT user, SUM(points) AS points_total 
FROM myTable 
GROUP BY user 

2)指出,過去一個月

SELECT user, SUM(points) AS points_month 
FROM myTable 
WHERE date_achieved >= CURRENT_DATE - INTERVAL 1 MONTH 
GROUP BY user 

什麼是一個單一的查詢實現這一目標的最佳途徑中積累?

非常感謝。

回答

5

只要使用case語句只在滿足條件時才計算點數。

SELECT 
     user, 
     SUM(points) AS points, 
     SUM(case 
      when date_achieved >= (CURRENT_DATE - INTERVAL 1 MONTH) 
      THEN points 
      else 0 END) points_last_Month 
FROM myTable 
GROUP BY user 
+0

,完美的工作,謝謝! – gjb

1
 
select 
    user, 
    sum(points) as points_total, 
    sum(
     case 
      when date_achieved >= current_date - interval 1 month then points 
      else 0 
     end 
    ) as points_month 
from myTable 
group by user 
+0

謝謝你的回答。 – gjb

相關問題