Question

The table has two columns, the ID is the PK and the other column is Type, sample data looks like the following.

| ID | Type | 
| 1  |  0   | 
| 2  |  0   | 
| 3  |  1   | 
| 4  |  1   | 
| 5  |  0   | 
| 6  |  1   | 

I was trying to group the sample data into the following desired output. 1. The desired output is ordered by ID. 2. The Category is calculated based on the following logic,continuous records with the same type will be assigned the same category, and records with different types will increase category by 1.

| ID | Type |Category | 
| 1  |  0   |    1    | 
| 2  |  0   |    1    |
| 3  |  1   |    2    |
| 4  |  1   |    2    |
| 5  |  0   |    3    |
| 6  |  1   |    4    |

Is it able to do it in SQL server 2008 and 2012? I found this (http://explainextended.com/2011/02/18/things-sql-needs-series/) might be able to resolve it.

Thanks in advance

No correct solution

OTHER TIPS

It is possible but a bit weird since the value for Category depends on previous data entries. Look at ROW_NUMBER() and DENSE_RANK() functions, which will do part of the numbering for you. I'd probably select a derived table ordering how you want and with row_number() to sequence them, join that back onto itself and compare rows with their previous one to see if Type matches and Id = Id-1, then re-rank based on that.

You might try (all in sql with the mapping in the sql query)

 select PK, ID, Category
   from (select PK, ID, "1" as 'Category' from Table1 where ID = 0 and PK < 3;
         UNION
         select PK, ID, "2" as 'Category' from Table1 where ID = 1 and PK < 5
         UNION
         select PK, ID, "3" as 'Category' from Table1 where PK = 5
         UNION
         select PK, ID, "4" as 'Category' from Table1 where PK = 6
        }
   order by PK

may this you are looking for

DECLARE @amount TABLE (ID INT,TYPE INT)

INSERT INTo @amount (ID,TYPE)VALUES (1,0)
INSERT INTo @amount (ID,TYPE)VALUES (2,0)
INSERT INTo @amount (ID,TYPE)VALUES (3,1)
INSERT INTo @amount (ID,TYPE)VALUES (4,1)
INSERT INTo @amount (ID,TYPE)VALUES (5,0)
INSERT INTo @amount (ID,TYPE)VALUES (6,1)
INSERT INTo @amount (ID,TYPE)VALUES (7,0)

select ID,TYPE,DENSE_RANK()OVER (PARTITION BY TYPE ORDER BY ID ASC ) AS RN  from @amount
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top