【问题标题】:Oracle Query to Join Two Tables based on Conditions & Group ByOracle 查询根据条件和分组方式连接两个表
【发布时间】:2021-12-07 11:34:18
【问题描述】:

我有以下格式的表格,

表 1

Bank Category Month_Year Loan_Type Outstanding
SI R1 JAN-21 Home 10
SI R1 JAN-21 Land 50
SI R2 FEB-21 Home 30
SI R2 MAR-21 Car 40

表 2

Bank Loan_Type
SI Home
SI Land
SI Car
SI Jewel
SI Education

我想使用连接/查询将表 A 和 B 转换为以下格式。表 2 中的数据(所有行)应根据 Category 和 Month_Year 添加。

BANK Category Month_Year Loan_Type Outstanding
SI R1 JAN-21 Home 10
SI R1 JAN-21 Land 50
SI R1 JAN-21 Car 0
SI R1 JAN-21 Jewel 0
SI R1 JAN-21 Education 0
SI R2 FEB-21 Home 30
SI R2 FEB-21 Land 0
SI R2 FEB-21 Car 0
SI R2 FEB-21 Jewel 0
SI R2 FEB-21 Education 0
SI R2 MAR-21 Home 0
SI R2 MAR-21 Land 0
SI R2 MAR-21 Car 40
SI R2 MAR-21 Jewel 0
SI R2 MAR-21 Education 0

【问题讨论】:

    标签: sql oracle join


    【解决方案1】:

    创建所需的所有项目的列表并左加入 Table1。例如

    select items.Bank, items.Category, items.Month_Year, items.Loan_Type, coalesce(t1.Outstanding, 0) Outstanding
    from (
        select t2.Bank, t2.Loan_Type, my.Month_Year,  cat.Category
        from (select distinct Month_Year
              from Table1) my
        cross join (select distinct Category
              from Table1) cat
        cross join Table2 t2
        ) items
    left join Table1 t1 on items.Bank = t1.Bank and items.Loan_Type = t1.Loan_Type and items.Month_Year = t1.Month_Year and items.Category = t1.Category;
    

    如果存在表Categories 替换它而不是查询中的派生类别。您可能还希望从参数生成一组 Month_Year 或使用日历表。

    【讨论】:

      【解决方案2】:

      主要是 CategoryMonth_Year 列被明确选择之后的表中需要一个 CROSS JOIN ,并且 Outstanding 列在主查询中添加为零以表示不匹配的值,否则返回它的值作为

      SELECT t2.Bank, t2.Category, t2.Month_Year, t2.Loan_Type, 
             NVL(t1.Outstanding,0) AS Outstanding
        FROM (SELECT *
                FROM (SELECT DISTINCT Category, Month_Year FROM table1) 
               CROSS JOIN table2) t2
        LEFT JOIN table1 t1
          ON t2.Category = t1.Category
         AND t2.Month_Year = t1.Month_Year
         AND t2.Loan_Type = t1.Loan_Type
       ORDER BY t2.Category, t2.Month_Year, t1.Outstanding NULLS LAST
      

      Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-18
        • 2020-04-12
        • 1970-01-01
        • 1970-01-01
        • 2021-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多