我在stackoverflow和网络上过去两天研究了这个,但仍然没有得到我想要的结果。我正在使用ORACLE 11G。我有两个带有两个不同ORDER BY子句的SQL查询。两者都必须保留正确的排序顺序。我只想将两者结合起来并删除重复项。我已经尝试过UNION从我的查询中删除重复项并且它可以工作,但不会保留我的组合查询的排序顺序。如何删除重复项并为每个SQL查询保留正确的排序顺序? 以下是我的查询,它正确排序但确实删除了重复项。我需要做什么?所有2018日期在整个查询结果集中重复一次。我不想要重复。谢谢您的帮助。
以下是我在下面合并的两个查询(这是最常见的查询):
SELECT FLIGHT_NMBR, SCHEDULED_LAUNCH_DATE
FROM FLIGHTS
WHERE to_date(scheduled_launch_date, 'DD-MON-YY')
BETWEEN add_months(trunc(sysdate, 'MON'),0)
AND add_months(trunc(sysdate, 'MON'),6)
AND DATA_VERSION_NAME = 'WORKING'
AND sequence_nmbr >= 0
ORDER BY SCHEDULED_LAUNCH_DATE ASC;
这是查询的底部:
SELECT FLIGHT_NMBR, SCHEDULED_LAUNCH_DATE
FROM FLIGHTS
WHERE DATA_VERSION_NAME = 'WORKING'
AND SEQUENCE_NMBR >= 0
ORDER BY sequence_nmbr asc;
然后,这是我提出的组合查询,它不像我想要的那样工作。我只想从下面的查询中删除重复项。我怎么能这样做?
WITH CTE_Sets AS (
SELECT 1 AS set_order, FLIGHT_NMBR, SCHEDULED_LAUNCH_DATE
FROM flights
WHERE to_date(scheduled_launch_date, 'DD-MON-YY')
BETWEEN add_months(trunc(sysdate, 'MON'),0)
AND add_months(trunc(sysdate, 'MON'),6)
AND DATA_VERSION_NAME = 'WORKING'
AND sequence_nmbr >= 0
UNION
SELECT 2 AS set_order, FLIGHT_NMBR, SCHEDULED_LAUNCH_DATE
FROM flights
WHERE DATA_VERSION_NAME = 'WORKING'
AND SEQUENCE_NMBR >= 0
)
SELECT FLIGHT_NMBR, SCHEDULED_LAUNCH_DATE
FROM CTE_Sets
ORDER BY
set_order,
CASE set_order
WHEN 1 THEN SCHEDULED_LAUNCH_DATE END ASC,
case set_order
WHEN 2 THEN SCHEDULED_LAUNCH_DATE END ASC;
上面我的UNION查询的结果:
FLIGHT_NMBR SCHEDULED
------------ ---------
SpX-14 26-JAN-18
69P 09-FEB-18
SpX-DM1 09-MAR-18
54S 13-MAR-18
OA-9 14-MAR-18
55S 29-APR-18
SpX-15 06-JUN-18
SpX-DM2 22-JUN-18
70P 27-JUN-18
1A/R 20-NOV-98
2A 04-DEC-98
答案 0 :(得分:1)
在order by
子句中完成工作:
SELECT FLIGHT_NMBR, SCHEDULED_LAUNCH_DATE
FROM FLIGHTS
WHERE DATA_VERSION_NAME = 'WORKING' AND
sequence_nmbr >= 0
ORDER BY (CASE WHEN to_date(scheduled_launch_date, 'DD-MON-YY') BETWEEN add_months(trunc(sysdate, 'MON'), 0) AND add_months(trunc(sysdate, 'MON'), 6) THEN 1 ELSE 2 END),
(CASE WHEN to_date(scheduled_launch_date, 'DD-MON-YY') BETWEEN add_months(trunc(sysdate, 'MON'), 0) AND add_months(trunc(sysdate, 'MON'), 6) THEN SCHEDULED_LAUNCH_DATE END),
sequence_nmbr;
注意:您应该将scheduled_launch_date
存储为日期列,而不是字符列。