如何在sql server中为每10行生成一个序列号

时间:2014-10-28 07:06:42

标签: sql-server

在选择中,我需要每10行一个序列号

对于前10行1,对于11到20行2,21到30行3,如...

提前致谢

2 个答案:

答案 0 :(得分:1)

试试这个。

WITH cte
     AS (SELECT 1 id
         UNION ALL
         SELECT id + 1
         FROM   cte
         WHERE  id < 20)
SELECT ( Row_number()
           OVER(
             ORDER BY id) - 1 ) / 10 + 1 AS seq,
       id
FROM   cte 

但是这只会按照某些列的顺序创建数字而不是表格。

答案 1 :(得分:0)

假设'someTable'作为您的表,并且没有任何关于具有顺序ID的列的假设,以下将通过对行进行编号然后对每10行进行分类来起作用:

WITH someTable as
(
    SELECT top 100 o1.* FROM sys.objects o1 cross join sys.objects o2
),
numberedTable AS
(
    SELECT someTable.name, ROW_NUMBER() OVER (ORDER BY object_id) AS rowNum
    FROM someTable
)
SELECT name, rowNum, CAST(rowNum / 10 AS INT) + 1 AS sequence10Items
FROM numberedTable;

SqlFiddle here