【问题标题】:Oracle - Count a select based on a subqueryOracle - 根据子查询计算选择
【发布时间】:2021-10-15 04:08:00
【问题描述】:

我需要根据主查询统计子查询的结果

我想计算一下 2021 年有多少辆汽车。

我将如何生成此查询的结果,其中有一列计算每辆具有 2021 年的绿色汽车。示例如下

表 1

ID Vehicle
1 Car
2 motorcycle
3 bicycle

表 2

ID ID_TABLE1 COLOR
1 2 RED
2 1 GREEN
3 3 BLACK
4 1 GREEN

表 3

ID ID_TABLE1 YEAR
1 2 2021
2 1 2020
3 3 2021
3 1 2020

我的尝试,它不起作用

select t1.Vehicle, t2.color from table1 t1 inner join table2 t2 on t1.id = t2.id_table1 
left joint(select count* table 3 t3 where t3.year = 2020 ) tbyear on t1.id = t3.id_table1

决赛桌如下所示:

NAME NAME COUNT
CAR green 2
motorcycle red 0
bicycle black 0

【问题讨论】:

    标签: sql oracle plsql subquery


    【解决方案1】:

    看起来你想要outer apply():

    select 
     t1.Vehicle, t2.color, tbyear.*
    from table1 t1 
         inner join table2 t2 
               on t1.id = t2.id_table1 
         outer apply(
            select count(*) cnt 
            from table3 t3 
            where t1.id = t3.id_table1 
            and t3.year = 2020
         ) tbyear;
    

    带有测试数据的完整示例:

    with -- test data:
     Table1(ID,Vehicle) as (
    select 1, 'Car'        from dual union all
    select 2, 'motorcycle' from dual union all
    select 3, 'bicycle'    from dual 
    )
    ,Table2(ID, ID_TABLE1, COLOR) as (
    select 1, 2, 'RED'   from dual union all
    select 2, 1, 'GREEN' from dual union all
    select 3, 3, 'BLACK' from dual union all
    select 4, 1, 'GREEN' from dual
    )
    ,Table3(ID,ID_TABLE1,YEAR) as (
    select 1, 2, 2021 from dual union all
    select 2, 1, 2020 from dual union all
    select 3, 3, 2021 from dual union all
    select 3, 1, 2020 from dual
    )
    -- end test data
    select 
     t1.Vehicle, t2.color, tbyear.*
    from table1 t1 
         inner join table2 t2 
               on t1.id = t2.id_table1 
         outer apply(
            select count(*) cnt 
            from table3 t3 
            where t1.id = t3.id_table1 
            and t3.year = 2020
         ) tbyear 
    

    结果:

    EHICLE    COLOR        CNT
    ---------- ----- ----------
    motorcycle RED            0
    Car        GREEN          2
    bicycle    BLACK          0
    Car        GREEN          2
    

    【讨论】:

      【解决方案2】:

      如果你想查看年份、车辆、颜色,它应该是这样的

      select t3.Year, t1.Vehicle, t2.color, COUNT(*)
      from table1 t1 
      inner join table2 t2 on t1.id = t2.id_table1 
      inner join table3 t3 on t1.id = t3.id_table1 
      GROUP BY t3.Year, t1.Vehicle, t2.color
      

      如果您不需要某些文件 - 在 select 和 group by 中删除它。

      但这不是最好的解决方案 - 例如,当您在 2021 年没有销售 Green Car 时 - 您不会在结果查询中看到它,这就是我应该问的原因:您需要查看它吗? (例如 0 而不是跳过这一行)

      我对任务的看法正确吗?

      【讨论】:

        猜你喜欢
        • 2015-11-25
        • 2013-12-21
        • 2013-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 2023-03-17
        • 1970-01-01
        相关资源
        最近更新 更多