>我正在尝试编写一个SQL查询,如果指定条件没有行,则可以将值显示为
0到目前为止,我已经尝试了以下内容,但似乎没有任何效果
-
coalesce(count(m.a),'0')
-
isnull(count(m.a),'0')
-
case when count(*) > 0 then count(*) else '0' end
select M.a, m.b, m.c, m.d, m.e,
--coalesce(count(m.a),'0') as CountOfRecords
--isnull(count(m.a),'0') as CountOfRecords
--case when count(*) > 0 then count(*) else '0' end
from my_table M
left join
(select a, b,c,d,e
from my_table
group by a, b,c,d,e
having count(*) >1 ) B
on M.b = B.b
and M.c = B.c
and M.d = B.d
and M.e = B.e
and m.a <> B.a
where M.a in (1,2)
and M.date<= '1/1/2019'
group by M.a, m.b, m.c, m.d, m.e
预期成果
A B C D E count
1 1 1 1 1 10
2 2 2 2 2 0
实际结果
A B C D E count
1 1 1 1 1 10
您需要使用嵌套请求:
select coalesce(nb, 0) from (
select count(*) nb from my_table
group by my_table.a
) nested;
你在寻找这样的东西吗?
select a, b, c, d, e,
sum(case when M.date <= '2019-01-01' then 1 else 0 end) as cnt
from my_table
where a in (1, 2)
group by a, b, c, d, e;
这会保留原始数据中与 a
上的条件匹配的所有行,但不一定与日期上的条件匹配。 然后,它仅计算与日期匹配的行。