我需要编写基于AIRCRAFTREG列选择最早小时的查询。发现最早的一小时后,它会被标记为' 1'和另一个(非首飞)与' 0'在FIRST_FLIGHT列中。 这是我的疑问:
select MIN(TO_CHAR(SCHEDULED_DEPDT_LC, 'DD-MM-YY HH24:MI')) SCHED_DEP,
AIRCRAFTREG,
CASE WHEN MIN(TO_CHAR(SCHEDULED_DEPDT_LC, 'DD-MM-YY HH24:MI'))
IN (TO_CHAR(SCHEDULED_DEPDT_LC, 'DD-MM-YYYY HH24:MI'))
THEN 1 ELSE 0 END FIRST_FLIGHT
from DBODSXML4OPS.XML4OPS
where STATUS IN ('Scheduled')
and SERVICETYPE IN ('J','G')
and ACTUAL_BLOCKOFF_LC is not null
and ACTUAL_BLOCKON_LC is not null
and (ACTUAL_BLOCKON_LC-SCHEDULED_ARRDT_LC)*24*60 > '+000000015 00:00:00.000000000'
and (ACTUAL_BLOCKOFF_LC-SCHEDULED_DEPDT_LC)*24*60 > '+000000015 00:00:00.000000000'
and TO_CHAR(SCHEDULED_DEPDT_LC, 'yyyy-mm-dd') BETWEEN '2018-05-02' and '2018-05-02'
group by AIRCRAFTREG, SCHEDULED_DEPDT_LC
order by AIRCRAFTREG;
结果:
+----------------+-------------+--------------+
| SCHED_DEP | AIRCRAFTREG | FIRST_FLIGHT |
+----------------+-------------+--------------+
| 02-05-18 14:25 | PK-GAA | 0 |
| 02-05-18 16:55 | PK-GAI | 0 |
| 02-05-18 12:50 | PK-GAJ | 0 |
| 02-05-18 14:40 | PK-GAJ | 0 |
| 02-05-18 16:05 | PK-GAJ | 0 |
+----------------+-------------+--------------+
预期:
+----------------+-------------+--------------+
| SCHED_DEP | AIRCRAFTREG | FIRST_FLIGHT |
+----------------+-------------+--------------+
| 02-05-18 14:25 | PK-GAA | 1 |
| 02-05-18 16:55 | PK-GAI | 1 |
| 02-05-18 12:50 | PK-GAJ | 1 |
| 02-05-18 14:40 | PK-GAJ | 0 |
| 02-05-18 16:05 | PK-GAJ | 0 |
+----------------+-------------+--------------+
答案 0 :(得分:1)
我认为你需要一个analytic version of MIN函数而不是GROUP BY查询 一个简单的例子(演示:http://sqlfiddle.com/#!4/bb331/3)
SELECT SCHED_DEP,
AIRCRAFTREG,
CASE WHEN SCHED_DEP =
min( SCHED_DEP ) OVER (partition by AIRCRAFTREG )
THEN 1 ELSE 0 END as FIRST_FLIGHT
FROM Table1
-- WHERE your where conditions are here
order by AIRCRAFTREG, SCHED_DEP
| SCHED_DEP | AIRCRAFTREG | FIRST_FLIGHT |
|-----------------------|-------------|--------------|
| 2018-02-05 14:25:00.0 | PK-GAA | 1 |
| 2018-02-05 16:55:00.0 | PK-GAI | 1 |
| 2018-02-05 12:50:00.0 | PK-GAJ | 1 |
| 2018-02-05 14:40:00.0 | PK-GAJ | 0 |
| 2018-02-05 16:05:00.0 | PK-GAJ | 0 |
答案 1 :(得分:0)
首先你有一个拼写错误,你在选择中将YYYY char与YY进行比较。
其次我认为你需要在CASE语句中做一个子查询来找到aircraftreg代码的min(sched_dep)(它很难看,有更好的方法)。
按方法分组不允许您扫描所有其他行进行比较(只有同一行)。