How do I generate row number without using rownum() in sql server

前端 未结 4 568
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 22:37

I have the following table:

CREATE table prd
(
prdid varchar(10)
)
insert into prd values (\'prd1011\'),(\'prd1023\'),(\'prd4532\'),(\'prd2341\')


        
相关标签:
4条回答
  • 2021-01-14 23:11

    You've failed to specify SQL Server version or motivation for the request.

    A SQL Server 2012+ method

    SELECT prdid,
           COUNT(*) OVER (ORDER BY prdid ROWS UNBOUNDED PRECEDING)
    FROM prd
    

    SQL Fiddle

    0 讨论(0)
  • 2021-01-14 23:11

    I tried this and it worked but it is working only if the prdid column is unique:

    select prdid,
    (select COUNT(*) from prd p where p.prdid >= r.prdid)rnk
    from prd r order by rnk
    
    0 讨论(0)
  • 2021-01-14 23:21
    select *, (
        select count(*)
        from prd p2
        where p1.prdid >= p2.prdid
    ) as cnt
    from prd p1
    
    0 讨论(0)
  • 2021-01-14 23:31

    Solution for non-unique column:

    SELECT p.prdid, p.num - t.n + 1 as num
    FROM (
        SELECT p1.prdid, p1.cnt
            , (
                SELECT COUNT(*)
                FROM prd p2
                WHERE p2.prdid <= p1.prdid
            ) num
        FROM (
            SELECT p1.prdid, COUNT(*) cnt
            FROM prd p1
            GROUP BY p1.prdid
        ) p1
    ) p
    INNER JOIN (
        select 1 n union all select 2 union all
        select 3 union all select 4 union all select 5 union all
        select 6 union all select 7 union all select 8 union all
        select 9 union all select 10 union all select 11 union all
        select 12 union all select 13 union all select 14 union all
        select 15 union all select 16 union all select 17 union all
        select 18 union all select 19 union all select 20
    ) t ON t.n <= p.cnt
    

    Found here.

    0 讨论(0)
提交回复
热议问题