所以我有一个表格
+----+-----+
| id | Val |
+----+-----+
| 1 | 20 |
| 1 | 30 |
| 2 | 0 |
| 2 | 80 |
| 3 | 45 |
| 3 | 60 |
| 4 | 0 |
| 4 | 30 |
+----+-----+
我想对id列和Val列中的值进行分组。仅,如果其中一个值为零,则结果总和也应为零
对于上表,输出将是
+----+-------+
| id |SumVal |
+----+-------+
| 1 | 50 |
| 2 | 0 |
| 3 | 105 |
| 4 | 0 |
+----+-------+
我尝试在sum函数中使用条件语句(CASE和IF),但这些条件似乎只适用于各个元素。
任何指针?
答案 0 :(得分:4)
使用SUM
和IF
:
SELECT id, (SUM(val) * IF(val = 0, 0, 1)) AS SumVal FROM idval GROUP BY id;
答案 1 :(得分:1)
检查此简单查询。
select id ,SUM(val)
from #Table
where val=0
group by ID
union
select id ,SUM(val)
from #Table
where id not in (select id from #Table where val=0)
group by ID
OutPut:
答案 2 :(得分:0)
试试这个
select id,if(cast(val as signed),sum(val),0) as total from tbl_name group by id;