加入 SQL 查询

时间:2021-05-28 07:19:31

标签: oracle

我需要有关左连接 sql 查询的帮助:

第一次查询:

SELECT1

结果:

WEEK Type First_month
21      12   50
21      14   4

然后我有下一个查询(仅在另一个月不同 - 格式结果是相同的):

 Select 2

结果:

WEEK  Type Second_month
21      12   45
21      14   1

而且我需要这样的结果(我无法连接上面的查询):

<头>
WEEK 输入 第一个月 Second_month
21 12 50 45
21 14 4 1

谁能帮我如何组合这两个查询?

1 个答案:

答案 0 :(得分:2)

一种选择是将您当前的查询用作 CTE,然后简单地加入它们。像这样:

SQL> with
  2  first_query (week_kw, typ, first_month) as
  3    (select 21, 12, 50 from dual union all
  4     select 21, 14,  4 from dual
  5    ),
  6  second_query (week_kw, typ, second_month) as
  7    (select 21, 12, 45 from dual union all
  8     select 21, 14,  1 from dual
  9    )
 10  select a.week_kw, a.typ, a.first_month, b.second_month
 11  from first_query a join second_query b on a.week_kw = b.week_kw
 12                                        and a.typ = b.typ;

   WEEK_KW        TYP FIRST_MONTH SECOND_MONTH
---------- ---------- ----------- ------------
        21         12          50           45
        21         14           4            1

SQL>

硬编码两个查询的结果;在您的情况下,您可以将那些冗长的选择复制/粘贴到括号中,例如

with 
first_query (week_kw, typ, first_month) as
  (SELECT KW as Week_KW, typ,count (*) AS First_month
            FROM 
            (
    SELECT * 
            FROM
            (
      SELECT        leftDMC
      etc.
  ),
second_query (the same as the first one)
...

如果还有另一个查询,您将创建一个新的 CTE 并将其加入到其余查询中:

    ... ,
   third_query (week_kw, typ, second_month) as
     (select ...
     )  
   select a.week_kw, a.typ, a.first_month, b.second_month, c.third_month
   from first_query a join second_query b on a.week_kw = b.week_kw and a.typ = b.typ
                      join third_query  c on a.week_kw = c.week_kw and a.typ = c.typ
相关问题