MS-SQL的row_number()可以使用以下查询进行模拟,但我需要MS-SQL实现此查询。
SELECT @row_number:= IF(@column_name = column_name, @row_number+1, 1) AS row_no,
@column_name:= column_name AS column_name
FROM db_name, (SELECT @row_number := 0, @column_name := '') AS temp
ORDER BY column_name;
答案 0 :(得分:3)
SELECT *, ROW_NUMBER() OVER (ORDER BY column_name)
FROM db_name
修改
没有row_number()
select *, (
select count(*)
from db_name p2
where p1.column_name >= p2.column_name )
as cnt from db_name p1
根据Damien的评论编辑2
非row_number()版本仅在column_name列的内容不包含重复项时才有效。如果不是,则row_number结果列中将出现重复和跳过。
答案 1 :(得分:1)
我认为没有row_number()
的正确MS-SQL实现更像是:
with dn as (
select dn.*, checksum(newid()) as rnd
from db_name dn
)
select dn.*,
(select count(*)
from dn dn2
where dn2.column_name = dn.column_name and
dn2.rnd < db.rnd
)
from dn;
当然,如果id
列可用(每行唯一一列),那么最好使用它:
select dn.*,
(select count(*)
from db_name dn2
where dn2.column_name = dn.column_name and
dn2.id < db.id
)
from db_name dn;