我有一个简单的表,例如:
create table #test(x int, y int)
insert into #test values(null, 1)
insert into #test values(1, 1)
insert into #test values(1, 2)
insert into #test values(2, 2)
insert into #test values(3, 2)
Run Code Online (Sandbox Code Playgroud)
我需要通过分组获得总和,但如果组具有空值,则获取null而不是sum.我可以用两个查询来做到这一点:
1) select y, case when AVG(x)<>SUM(x)/COUNT(*) then null else SUM(x) end from #test
group by y
2) select y, CASE WHEN EXISTS(select * from #test innerTest where innerTest.y=outerTest.y and x is null) then null else sum(x) end
from #test outerTest group by y
Run Code Online (Sandbox Code Playgroud)
哪个查询性能更好?还有其他解决方案吗?
你可以检查组是否有这样的空值:
select
y,
case when count(x) <> count(*) then null else sum(x) end
from test
group by y
Run Code Online (Sandbox Code Playgroud)
我99.99%肯定这个会跑得比子查询更快.
| 归档时间: |
|
| 查看次数: |
982 次 |
| 最近记录: |