我正在尝试使用Yii框架在查询中执行SUM()并返回' Yii'方式。
我有一张名为' codes'具有以下结构(为清楚起见,我省略了所有不相关的列)
+--------+----------+-------------+
| user_id | points | classroom_id|
+---------+---------+-------------+
| 2 | 10 | 219 |
| 2 | 30 | 219 |
| 2 | -20 | 219 |
| 2 | 100 | 219 |
| 2 | -50 | 219 |
+--------+---------+--------------+
我的查询目前如下:
SELECT user_id, points, SUM(points) AS current_points
FROM `codes`
WHERE classroom_id = 219
GROUP BY user_id;
我基本上需要修改此查询以返回' total_points' (这些都是没有减去负数的点)
所以我希望: current_points - 70 total_points - 140
有人能建议最好的方法吗?
答案 0 :(得分:1)
使用符号函数过滤负值:
SELECT user_id, points, SUM(GREATEST(SIGN(points),0) * points) AS current_points
FROM `codes`
WHERE classroom_id = 219
GROUP BY user_id;
替代:
SUM ( CASE WHEN points > 0 THEN points ELSE 0 END )