问题描述
|
我有一个表,其中包含名为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
现在,猜测您的意思是结果集可能在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,ProductName
FROM
(
SELECT
ROW_NUMBER() OVER (ORDER BY ProductID) AS ContiguousProductID,ProductName,ProductID
FROM
dbo.Product
) P2