Facing issue in auto generation of serial number.
How can i use row_number()
in proper manner or is there any alternative to achieve the expected results?
Note: I want to write query without using CASE
.
SELECT row_number() over (order by COALESCE(legs.sta, legs.eta) ASC) sno, legs.Flight_ID flightId, legs.flight, legs.flightDate FROM Flt_OperativeFlight_Legs LEG ORDER BY COALESCE(legs.sta, legs.eta) ASC
Current Results:
+------+--------+-------------------------+ | sno | flight | flightDate | +------+--------+-------------------------+ | 1 | 3K0722 | 2019-01-08 17:10:00.000 | | 2 | 3K0722 | 2019-01-08 20:20:00.000 | | 3 | 3K0723 | 2019-01-09 17:10:00.000 | | 4 | 3K0724 | 2019-01-10 20:20:00.000 | +------+--------+-------------------------+
Expected Results:
+------+--------+-------------------------+ | sno | flight | flightDate | +------+--------+-------------------------+ | 1 | 3K0722 | 2019-01-08 17:10:00.000 | | | | 2019-01-08 20:20:00.000 | | 2 | 3K0723 | 2019-01-09 17:10:00.000 | | 3 | 3K0724 | 2019-01-10 20:20:00.000 | +------+--------+-------------------------+
Advertisement
Answer
You can try to use ROW_NUMBER
window function in a subquery, then use DENSE_RANK
window function to create no
column with CASE WHEN
expression get rn = 1
row.
SELECT (CASE WHEN rn = 1 THEN DENSE_RANK() over(order by flight) END) no, (CASE WHEN rn = 1 THEN flt_id END) flt_id, (CASE WHEN rn = 1 THEN flight END) flight, flightDate FROM ( SELECT *,ROW_NUMBER() OVER(PARTITION BY flt_id,flight ORDER BY flightDate) rn FROM Flt_OperativeFlight_Legs ) t1