Saravanan
Saravanan

Reputation: 930

Converting rows into columns tsql

I have a table like

CId| RId|  No
---+----+----
  1|  10| 100    
  1|  20|  20    
  1|  30|  10    
  2|  10| 200    
  2|  30|  20    
  3|  40|  25

here, RId represents "NoToAttend" (10),"NoNotToAttend" (20),"NoWait"(30),"Backup" (40) etc...

I need to have a result table that will look like

Cid|  "NoToAttend"|   "NoNotToAttend"| "NoWait"|  "Backup"
---+--------------+------------------+---------+----------
  1|           100|                20|     null|
  2|           200|              null|       20|     null
  3|          null|              null|     null|       25

I am not sure on how to use PIVOT. Need help on this

Upvotes: 0

Views: 1247

Answers (1)

GarethD
GarethD

Reputation: 69749

You can use the PIVOT Function and just alias your columns:

SELECT  pvt.CID,
        [NoToAttend] = pvt.[10],
        [NoNotToAttend] = pvt.[20],
        [NoWait] = pvt.[30],
        [Backup] = pvt.[40]
FROM    T
        PIVOT
        (   SUM([No])
            FOR RID IN ([10], [20, [30], [40])
        ) pvt;

Upvotes: 1

Related Questions