简体   繁体   中英

Can I use RowNumber to categorise my result set?

I have the following results set:

ItemNumber | Item  
1          | a  
2          | b  
1          | c  
2          | d  
3          | e  
1          | f  
2          | g

I want to categorise these so that the results set looks like:

ItemNumber | Item  
1          | a  
1          | b  
2          | c  
2          | d  
2          | e  
3          | f  
3          | g

This is as I want to be able to say that a and b are linked and so are categorised by the same RowNumber.

I am struggling in getting this to work using RowNumber Over Partition By...

Any suggestions on how to tackle this problem?

I have tried Row Number Over Partition By. This does not give my desired result:

SELECT ROW_NUMBER() OVER (PARTITION BY ItemNumber ORDER BY (SELECT NULL)) AS RowNumber,
       ItemNumber,
       Item
  FROM #List;

This gets you the result you are after, however, I doubt that it'll work on your production environment if what we have is overly simplified. If the values of Item are actually in alphabetical order in your database, then this will work. if not, the task you ask for is impossible, as there is no way to order your rows in the order from your original data with an ORDER BY clause.

Anyway, with the caveat, a conditional COUNT works:

SELECT COUNT(CASE V.ItemNumber WHEN 1 THEN 1 END) OVER (ORDER BY V.Item ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS ItemNumber,
       V.Item
FROM (VALUES(1,'a'),
            (2,'b'),
            (1,'c'),
            (2,'d'),
            (3,'e'),
            (1,'f'),
            (2,'g'))V(ItemNumber,Item);

You could achieve the above with ROW_NUMBER too, but a COUNT is the "easier" option in my opinion.

Edit: Appears that the is not using SQL Server 2012, is using an unsupported version of SQL Server. This answer will therefore not work; as you need a supported version (2012+) to use ROWS BETWEEN . I will leave this here anyway, in case the OP upgrades in the near future, which is strongly advised.

Why can't you use a simple CASE Statement:

SELECT CASE Item
         WHEN 'a' THEN 1
         WHEN 'b' THEN 1
         WHEN 'c' THEN 2
         WHEN 'd' THEN 2       
         WHEN 'e' THEN 2
         WHEN 'f' THEN 3    
         WHEN 'g' THEN 3
       END AS ItemNumber,
       Item
FROM myTable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM