Sql server 如何基于表主键分配交替行号?

Sql server 如何基于表主键分配交替行号?,sql-server,stored-procedures,sql,Sql Server,Stored Procedures,Sql,我有一个名为Product的数据表 ProductID ProductName 1 ABC 2 PQR 3 XYZ 4 HJK 5 LKJ 6 MNB ... .... 有更多的产品在里面。我希望在Select查询中得到如下结果: RowNo ProductID ProductName 1 1 ABC 1

我有一个名为Product的数据表

ProductID  ProductName
1            ABC
2            PQR
3            XYZ
4            HJK
5            LKJ
6            MNB
...          .... 
有更多的产品在里面。我希望在Select查询中得到如下结果:

RowNo ProductID ProductName
1      1           ABC
1      2           PQR
2      3           XYZ
2      4           HJK
1      5           LKJ
1      6           MNB
2      7           klj
2      8           hjg

然后1,1,2,2 1,1表示表中的记录数。有可能吗?如果有,我该怎么做?

这适用于假定ProductID是连续的示例数据:

SELECT
   CASE WHEN ProductID % 4 = 0 OR (ProductID+1) % 4 = 0 THEN 2 ELSE 1 END,
   ProductID,
   ProductName
FROM
   Product
现在,我猜您的意思是在resultset中,ProductID中可能存在漏洞

SELECT
   CASE WHEN ContiguousProductID % 4 = 0 OR (ContiguousProductID+1) % 4 = 0 THEN 2 ELSE 1 END,
   --ContiguousProductID,
   --CASE WHEN ProductID % 4 = 0 OR (ProductID+1) % 4 = 0 THEN 2 ELSE 1 END,
   ProductID,
   ProductName
FROM
    (
    SELECT
        ROW_NUMBER() OVER (ORDER BY ProductID) AS ContiguousProductID,
        ProductName, ProductID
    FROM 
        dbo.Product
    ) P2

这适用于假定ProductID是连续的示例数据:

SELECT
   CASE WHEN ProductID % 4 = 0 OR (ProductID+1) % 4 = 0 THEN 2 ELSE 1 END,
   ProductID,
   ProductName
FROM
   Product
现在,我猜您的意思是在resultset中,ProductID中可能存在漏洞

SELECT
   CASE WHEN ContiguousProductID % 4 = 0 OR (ContiguousProductID+1) % 4 = 0 THEN 2 ELSE 1 END,
   --ContiguousProductID,
   --CASE WHEN ProductID % 4 = 0 OR (ProductID+1) % 4 = 0 THEN 2 ELSE 1 END,
   ProductID,
   ProductName
FROM
    (
    SELECT
        ROW_NUMBER() OVER (ORDER BY ProductID) AS ContiguousProductID,
        ProductName, ProductID
    FROM 
        dbo.Product
    ) P2

感谢@gbn我在同一个查询上得到了一些编辑结果,实际上我想对前两行应用1,然后对后两行应用2,而不管数据如何。感谢@gbn我在同一个查询上得到了一些编辑结果,实际上我想对前两行应用1,然后对后两行应用2,而不管数据如何。