首页 > 解决方案 > 自联接表并将两个查询中的联接列包含为单列

问题描述

所以这是我的桌子

Machine No | Cut off Date | status    | event number
================================================
        12 | 01-DEC-2018  | Pending   | 8888
        23 | 01-DEC-2018  | Available | 9999
        12 | 01-DEC-2019  | Available | 8888
        23 | 01-DEC-2019  | Available | 9999
        66 | 01-DEC-2018  | Pending   | 6666

预期结果: cy(Current Year)- 2018 ly(Last Year)-2017

Machine_No |  cy_status   | cy_event number|ly_status |ly_event_number
==================================================================
   12      |  Pending     |  8888          |Available | 8888
   23      |  Available   |  9999          |Available | 9999
   66      |  NULL        |  NULL          |Pending   | 6666

我当前的查询和结果:

    SELECT  cy.Machine_No AS Mac_No, ly.Machine_No AS Mac_no, 
    CY_EVENT_NUM, CY_STATUS,
        LY_EVENT_NUM,
        LY_STATUS from
         (      SELECT
                  machine_number AS Machine_No, EVENT_NUMBER AS 
    CY_EVENT_NUM, STATUS AS CY_STATUS
        FROM
          center c
        WHERE
          cut_off_date = '01-DEC-2018'
        AND machine_number IN ('6666', '7777', '8888', '9999')) cy 
    FULL OUTER JOIN (
        SELECT
          machine_number AS Machine_No , EVENT_NUMBER AS 
    LY_EVENT_NUM, STATUS AS LY_STATUS
        FROM
          center c1
        WHERE
          cut_off_date = '01-DEC-2017'
        AND machine_number IN ('6666', '7777', '8888', '9999') )ly 
    on  
    cy.Machine_No= ly.Machine_No'''

结果

Mac_No|Mac_No|cy_status     |cy_event number |ly_status|ly_event_number
=====  =====    ======        ==============   ========  =========
   12 | NULL |  Pending     |  8888          |Available| 8888
   23 | NULL |  Available   |  9999          |Available| 9999
  NULL| 66   |  NULL        |  NULL          |   NULL  | 7777

我 cy.Mac_no 和 ly.Mac_no 在同一列。

有人可以帮我实现这一目标吗?

标签: sqldatetimepivotfull-outer-join

解决方案


我认为可以通过使用条件聚合来简化您的查询,如下所示:

select 
    machin_no,
    max(case when extract(year from cut_off_date) = 2018 then status end) cy_status,
    max(case when extract(year from cut_off_date) = 2018 then event_number end) cy_event_number,
    max(case when extract(year from cut_off_date) = 2017 then status end) ly_status,
    max(case when extract(year from cut_off_date) = 2017 then event_number end) ly_event_number
from center
group by machine_no

你处理日期的方式对我来说不是很清楚,所以我只根据年份进行查询(cut_off_date 是2017,或2018)。

如果您需要过滤一个确切的日期,那么您可以更改条件最大值,如下所示:

max(case when cut_off_date = to_date('2018-12-01', 'yyyy-mm-dd') then status end) cy_status,
... and so on ...

上面的表达式假设您使用的是 oracle。


推荐阅读