我有一张桌子:
------------------------
|id|p_id|desired|earned|
------------------------
|1 | 1 | 5 | 7 |
|2 | 1 | 15 | 0 |
|3 | 1 | 10 | 0 |
|4 | 2 | 2 | 3 |
|5 | 2 | 2 | 3 |
|6 | 2 | 2 | 3 |
------------------------
我需要进行一些计算,并尝试在一个非常复杂的请求中进行计算,否则我知道如何使用请求数来计算它。 我需要结果表如下:
---------------------------------------------------------
|p_id|total_earned| AVG | Count | SUM |
| | | (desired)|(if earned != 0)|(desired)|
---------------------------------------------------------
| 1 | 7 | 10 | 1 | 30 |
| 2 | 9 | 2 | 3 | 6 |
---------------------------------------------------------
我到目前为止构建了:
SELECT p_id, SUM(earned), AVG(desired), Sum(desired)
FROM table GROUP BY p_id
但我无法弄清楚如何计算有条件的分组记录数。我可以使用HAVING
获取此号码,但是在单独的请求中。
我几乎可以肯定SQL应该拥有这种能力。
答案 0 :(得分:12)
您可以使用CASE
表达式。
试试这个,
SELECT p_id
,SUM(earned) AS total_earned
,AVG(desired) AS avg_desired
,COUNT(CASE WHEN Earned!=0 THEN 1 END) AS earned_count
,SUM(desired) AS sum_desired
FROM table
GROUP BY p_id;
答案 1 :(得分:3)
您几乎已经完成了查询,只需在case
表达式的帮助下添加条件聚合以获得收入计数
SELECT
p_id,
SUM(earned) [total_earned],
AVG(desired) [desired],
SUM(CASE WHEN earned <> 0 THEN 1 ELSE 0 END) [COUNT],
SUM(desired) [SUM] FROM <table>
GROUP BY p_id
结果
p_id total_earned desired COUNT SUM
1 7 10 1 30
2 9 2 3 6
答案 2 :(得分:3)
CASE
的缩写替代
SELECT p_id,
SUM(earned) AS total_earned,
AVG(desired) AS average_desired,
COUNT(earned != 0 OR NULL) AS earned_count,
SUM(desired) AS sum_desired
FROM table GROUP BY p_id;
因为NULL
不计算在内。
答案 3 :(得分:1)
NULLIF()
是标准SQL,可能最短:
SELECT p_id
, count(NULLIF(earned, 0)) AS earned_count
-- , more ...
FROM table
GROUP BY 1;
count()
仅计算非空值。
更多变种: