我有一张这样的表:
C1 | C2
-----|----
23 | 10
null | 10
23 | 10
24 | 10
24 | 10
我希望按C1分组并在23和24的总和(C2)中计算null的C2值
SELECT C1, sum(C2) FROM table
GROUP BY C1
查询返回此表:
C1 | C2
-----|----
23 | 20
null | 10
24 | 20
但我想要这个:
C1 | C2
-----|----
23 | 30
24 | 30
是否有可能得到这样的结果?
答案 0 :(得分:2)
像以前一样做GROUP BY
,但也要为所有空值c1添加一个总和为c2的子选择:
select c1, sum(c2) + (select sum(c2) from table where c1 is null)
from table
where c1 is not null
group by c1
Core-99 ANSI SQL。
答案 1 :(得分:1)
这应该有效(我在MySQL中测试过):
SELECT C1, sum(C2) + @runtot AS sum
FROM (SELECT @runtot:= SUM(C2) from mytable t where t.C1 IS NULL) c,
mytable
WHERE C1 IS NOT NULL
GROUP BY C1