这是查询,我们没有 location# =83 的数据,但我希望输出为 cnt=0
SELECT
COUNT(1) AS cnt , location# as record_no
FROM
test
WHERE
cny# = 1
AND location# = 83 group by location#
将输出作为空行,而不是像这样期望输出
cny
---|-----
1 0
通过以下查询我得到了预期的输出
SELECT
COUNT(1) AS cnt
FROM
test
WHERE
cny# = 1
AND location# =83
如何通过使用 group by 并在 select 中添加列来获得与上面预期相同的输出,就像我在顶部查询中显示的那样
样本数据:
SQL> select * from test;
LOCATION# CNY#
---------- ----------
1 1
1 1
83 22
如您所知,这有效:
SQL> select count(*)
2 from test
3 where cny# = 1
4 and location# = 83;
COUNT(*)
----------
0
你想看到 zero 和
location# = 83
,但是 - 没有:
SQL> select location#, count(*)
2 from test
3 where cny# = 1
4 and location# = 83
5 group by location#;
no rows selected
一种选择是使用自连接;只是为了检查没有过滤器的情况
location#
:
SQL> select a.location#, count(distinct b.rowid) cnt
2 from test a left join test b on a.location# = b.location# and a.cny# = 1
3 --where a.location# = 83
4 group by a.location#;
LOCATION# CNT
---------- ----------
83 0
1 2
带过滤器:
SQL> select a.location#, count(distinct b.rowid) cnt
2 from test a left join test b on a.location# = b.location# and a.cny# = 1
3 where a.location# = 83
4 group by a.location#;
LOCATION# CNT
---------- ----------
83 0