首页 > 解决方案 > 为什么与子查询的连接没有返回并匹配所有值?

问题描述

这是我的代码。

select trunc(q1.ex_date) as ex_date, 
count(*),
q2.total_cnt
from main_table q1
left join (select 
       trunc(ex_date) as ex_date, 
        count(*) total_cnt
        from main_table
        group by trunc(ex_date)) q2 on q2.ex_date =trunc(q1.ex_date)
group by trunc(q1.ex_date);

目前,它正在产生以下结果:

EX_DATE             COUNT(*) TOTAL_CNT
09-NOV-20 00:00:00  681      207
10-NOV-20 00:00:00  739      207
11-NOV-20 00:00:00  449      207
12-NOV-20 00:00:00  762      207
13-NOV-20 00:00:00  566      207
14-NOV-20 00:00:00  207      207
15-NOV-20 00:00:00  207      207

total_cnt 列重复相同的值。它应该与子查询的结果连接,如下所示:

15-NOV-20 00:00:00  207
16-NOV-20 00:00:00  458
09-NOV-20 00:00:00  681
10-NOV-20 00:00:00  739
12-NOV-20 00:00:00  762
11-NOV-20 00:00:00  449
13-NOV-20 00:00:00  566
14-NOV-20 00:00:00  207

有谁知道为什么加入没有给我来自子查询的 total_cnt

标签: sqloracle

解决方案


您不应该得到任何结果,因为您编写的查询无效。您有一个聚合查询,但q2.total_cnt即使您选择它,您也没有聚合或分组。

在旧版本的 Oracle(主要是 12.1 以及横向视图转换旁边)中存在一些错误,它会忽略这一点,将查询转换为它可以执行的东西并给你一个结果。

您的查询可能看起来像

select trunc(q1.ex_date) as ex_date, 
count(*),
q2.total_cnt
from main_table q1
left join (select 
       trunc(ex_date) as ex_date, 
        count(*) total_cnt
        from main_table
        group by trunc(ex_date)) q2 on q2.ex_date =trunc(q1.ex_date)
group by trunc(q1.ex_date)
,q2.total_cnt;

推荐阅读