序列号自动生成

时间:2019-01-10 10:26:11

标签: sql sql-server tsql

自动生成序列号时遇到问题。

我该如何以正确的方式使用row_number()还是有其他选择来达到预期的效果?

注意:我想不使用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

当前结果:

+------+--------+-------------------------+
| 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 |
+------+--------+-------------------------+

预期结果:

+------+--------+-------------------------+
| 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 |
+------+--------+-------------------------+

4 个答案:

答案 0 :(得分:2)

您需要其他row_number()

SELECT DENSE_RANK() OVER (ORDER BY flt_id, flight) AS Sr,
       (CASE WHEN Seq = 1 
             THEN flightId
        END) AS Flight_ID,
       (CASE WHEN Seq = 1 
             THEN flight
        END) AS flight, flightDate
FROM (SELECT ROW_NUMBER() OVER(PARTITION BY Flight_ID, flight ORDER BY flightDate) AS Seq,
             legs.Flight_ID flightId, legs.flight, legs.flightDate
      FROM Flt_OperativeFlight_Legs LEG
     ) l;

答案 1 :(得分:2)

您可以尝试在子查询中使用ROW_NUMBER窗口函数,然后使用DENSE_RANK窗口函数创建带有no表达式的CASE WHEN列,以获取rn = 1

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

sqlfiddle

答案 2 :(得分:1)

您可以使用DENSE_RANK代替ROW_NUMBER

SELECT 
 DENSE_RANK() over (order by COALESCE(legs.sta, legs.eta, legs.ata) ASC) as "s.no",
 legs.Flight_ID flightId
 ,legs.flight
 ,legs.flightDate
FROM Flt_OperativeFlight_Legs LEG
ORDER BY COALESCE(legs.sta, legs.eta, legs.ata) ASC

答案 3 :(得分:1)

请参考以下解决方案,以清空我使用CASE表达式所需的重复数据

在CTE表达式中,我结合使用了Row_Number和Dense_Rank函数和Partition By clause

;with cte as (
    select
        ROW_NUMBER() over (order by flight, flightDate) as num,
        DENSE_RANK() over (order by flight) as [no],
        ROW_NUMBER() over (partition by flight order by flightDate) as rn,
        flight,
        flightDate
    from Flt_OperativeFlight_Legs legs
)
select
    case when rn > 1 then null else [no] end as [no],
    case when rn > 1 then null else flight end as flight,
    flightDate
from cte
order by num

输出如下

enter image description here