Sanjay Janardhan
Sanjay Janardhan

Reputation: 37

SQL Server Unpivot the data by mapping the columns as Key Value pairs

I have a requirement to map the values from two columns to map the values-

Screenshot of the Original Data that needs to be done UnPivot: enter image description here

Example-

S1 S1Date
S2 S2Date
S3 S3Date
S4 S4Date

Data-

Cricket      2018-04-07 20:45:22.387
FootBall     2018-04-08 20:45:22.387
TableTennis  2018-04-09 20:45:22.387
Badminton    2018-04-10 20:45:22.387

I tried unpivot and was not sure how to map multiple columns. Please assist.

Upvotes: 0

Views: 353

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270401

I would do this using apply:

select v.*
from t cross apply
     (values (s1, s1date), (s2, s2date), (s3, s3date), (s4, s4date)) v(col, dte);

unpivot does a very specific thing -- I don't think it is even worth learning the syntax. On the other hand, apply is an introduction to lateral joins, which are very powerful. Unpivot is a good way to start learning about them.

Upvotes: 4

Related Questions