oracle SQL查找另一个表以进行聚合并将其合并回外部查询

hof1towb  于 2023-01-20  发布在  Oracle
关注(0)|答案(2)|浏览(87)

查询:能够执行从表A到表B的查找,并使用基于引用表A中的日期字段和表B中的日期字段的日期条件的聚合函数。
场景:
我有一个汽车表(包含汽车ID、汽车开始日期、汽车结束日期)和一个汽车付款表(包含汽车ID、汽车付款日期、汽车付款金额)。
对于car表中的每辆车,我想使用CAR_ID在car_payments表中进行查找,并使用Car_Payment_DT计算Car_START_DT和Car_END_DT(来自car表)之间的Car_Payment_Amt记录数,从而进行聚合。
我尝试在car_payments表下创建一个COUNT(Car_Payment_Amt)GROUP BY CAR_ID子查询,并基于CAR_ID将其与Car表JOIN以获取结果,但意识到随着数据大小的增加,子查询所需的时间将比预期的要长。
我如何使用SQL来高效地完成这项工作?我做了一个搜索,人们说使用相关查询会有性能瓶颈。还有其他选择吗?

7ajki6be

7ajki6be1#

只需使用简单的连接

select
    c.car_id, count(cp.payment_amt) as pmt_count
from
    car c 
    left join
    car_payment cp on cp.car_id = c.car_id 
        and cp.payment_dt between c.car_start_dt and c.car_end_date
group by
    c.car_id
r3i60tvu

r3i60tvu2#

您可以尝试不分组,如这里:

SELECT  c.CAR_ID, 
        (Select Count(*) From payments 
         Where CAR_ID = c.CAR_ID And PAY_DATE Between c.START_DATE And c.END_DATE) "NO_OF_PAYS"
FROM    cars c

其样本数据如下:

WITH
    cars (CAR_ID, START_DATE, END_DATE) AS
        (
            Select 1, To_Date('01.01.2023', 'dd.mm.yyyy'), To_Date('04.01.2023', 'dd.mm.yyyy') From Dual Union All
            Select 2, To_Date('01.01.2023', 'dd.mm.yyyy'), To_Date('06.01.2023', 'dd.mm.yyyy') From Dual Union All
            Select 3, To_Date('03.01.2023', 'dd.mm.yyyy'), To_Date('08.01.2023', 'dd.mm.yyyy') From Dual Union All
            Select 4, To_Date('03.01.2023', 'dd.mm.yyyy'), To_Date('10.01.2023', 'dd.mm.yyyy') From Dual Union All
            Select 5, To_Date('05.01.2023', 'dd.mm.yyyy'), To_Date('12.01.2023', 'dd.mm.yyyy') From Dual Union All
            Select 6, To_Date('07.01.2023', 'dd.mm.yyyy'), To_Date('14.01.2023', 'dd.mm.yyyy') From Dual 
        ),
    payments (CAR_ID, PAY_DATE, AMAUNT) AS
        (
            Select 1, To_Date('01.01.2023', 'dd.mm.yyyy'), 100 From Dual Union All
            Select 1, To_Date('03.01.2023', 'dd.mm.yyyy'), 100 From Dual Union All
            Select 1, To_Date('05.01.2023', 'dd.mm.yyyy'), 100 From Dual Union All
            Select 1, To_Date('06.01.2023', 'dd.mm.yyyy'), 100 From Dual Union All
            Select 3, To_Date('05.01.2023', 'dd.mm.yyyy'), 300 From Dual Union All
            Select 3, To_Date('08.01.2023', 'dd.mm.yyyy'), 300 From Dual Union All
            Select 3, To_Date('11.01.2023', 'dd.mm.yyyy'), 300 From Dual Union All
            Select 5, To_Date('11.01.2023', 'dd.mm.yyyy'), 500 From Dual Union All
            Select 5, To_Date('13.01.2023', 'dd.mm.yyyy'), 500 From Dual Union All
            Select 6, To_Date('06.01.2023', 'dd.mm.yyyy'), 600 From Dual Union All
            Select 6, To_Date('12.01.2023', 'dd.mm.yyyy'), 600 From Dual 
        )

...结果为

--  R e s u l t :
--      CAR_ID NO_OF_PAYS
--  ---------- ----------
--           1          2 
--           2          0 
--           3          2 
--           4          0 
--           5          1 
--           6          1

相关问题