2011-05-26 53 views
0

需要幫助我與它有更多的產品數據命名的產品在SQL查詢

ProductID ProductName 
1   ABC 
2   PQR 
3   XYZ 
4   HJK 
5   LKJ 
6   MNB 
...   .... 

的表。
正是我要的是結果這樣的選擇查詢:

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爲沒有在表中 記錄是有可能與否,如果可能的話怎麼有可能的?

回答

3

這適用於它假定您的ProductID樣本數據contiguoous現在

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 
+0

謝謝@gbn我有導致一些在相同的查詢上編輯實際上,我希望將1應用於前兩行,然後將2應用於後兩個,而與數據無關。 – gbbosmiya 2011-05-26 08:19:41