2

我有下表:

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

我需要在不使用 ROWNUM() 内置函数的情况下返回相同的行号。那可能吗?

4

4 回答 4

3

您未能为请求指定 SQL Server 版本或动机。

SQL Server 2012+ 方法

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

SQL小提琴

于 2013-09-17T14:26:55.330 回答
3
select *, (
    select count(*)
    from prd p2
    where p1.prdid >= p2.prdid
) as cnt
from prd p1
于 2013-09-17T13:49:51.533 回答
2

我试过这个并且它有效,但只有当 prdid 列是唯一的时它才有效:

select prdid,
(select COUNT(*) from prd p where p.prdid >= r.prdid)rnk
from prd r order by rnk
于 2013-09-17T13:49:59.633 回答
2

非唯一列的解决方案:

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

在这里找到。

于 2013-09-17T14:05:39.323 回答