我试图在一个查询中执行两个不同的SUM。
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
使用单个查询实现此目标的最佳方法是什么?
非常感谢。
答案 0 :(得分:5)
只需使用案例陈述,只在符合条件的情况下计算点数。
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
答案 1 :(得分: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