sql - 自联接表并将两个查询中的联接列包含为单列
问题描述
所以这是我的桌子
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 在同一列。
有人可以帮我实现这一目标吗?
解决方案
我认为可以通过使用条件聚合来简化您的查询,如下所示:
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。
推荐阅读
- java - Spring RestTemplate 布尔大写反序列化
- react-native - 如何在 wix react-native-navigation 中使用 pop 传递参数?
- android - java.lang.ClassCastException:kotlinx.coroutines.CompletableDeferredImpl 不能转换为 java.util.List?
- c# - 性能问题 Tesseract OcrApi C#
- c# - 如何在 Asp.net MVC 中加入两个表并将数据显示到表中
- mongodb - 如何在mongodb的find中进行查询
- php - 在 laravel 的 json 数组中查找
- interpreter - 我在使用 ghost4j api 在 java 中运行 postscript 文件时遇到问题。顺便说一句,我对ghostscript初始化参数知之甚少
- php - 尽管结果存储在会话中,但查询会在表单的每一页上执行
- python - 如何使用 python PyQt5 确定我的应用程序(窗口)的活动屏幕(监视器)?