CodingSoft
CodingSoft

Reputation: 397

Move Values from Rows to Columns in SQL Server 2008

I'm trying to get values stored like this in columns in sql server like below:

Mon| Tue| Wed| Thu| Fri| Sat| Sun
30 |  20| 30 | 10 | 30 | 15 | 25

to something like this:

Mon|30 
Tue|20 
Wed|30
Thu|10
Fri|30
Sat|15
Sun|25

Sample code will be appreciated. Thanks in advance.

Upvotes: 0

Views: 64

Answers (1)

Alisa
Alisa

Reputation: 3082

Suppose your table is t1: t1(mon, tue, wed, thu, fri, sat, sun)

Here's your answer:

select 'Mon' as day, mon as number from t1
union all
select 'Tue', tue from t1
union all
select 'Wed', wed from t1
union all
select 'Thu', thu from t1
union all
select 'Fri', fri from t1
union all
select 'Sat', sat from t1
union all
select 'Sun', sun from t1

In your result set, then, you'll have two fields: "day" and "number" as specified in the answer.

Upvotes: 1

Related Questions