Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
A little SQL quiz
Message
From
29/06/2014 13:57:53
 
 
To
All
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Title:
A little SQL quiz
Environment versions
SQL Server:
SQL Server 2005
Application:
Web
Miscellaneous
Thread ID:
01602842
Message ID:
01602842
Views:
87
This one is something that I'm sure database developers have run into. Data stored in columns that ideally should be stored in rows.

I'll keep the example very basic.
create table dbo.SalesTemp (SalesManID varchar(10), Jan decimal(14,4), Feb decimal(14,4), Mar decimal(14,4))
insert into SalesTemp values ('Salesman A', 100, 200, 300), 
                                          ('Salesman B', 400, 500, 600)
One row for each Salesman ID, and columns for monthly sales. Normally it would probably be more than 3 columns but just keeping it simple.

We want the result set to look like this:

SalesManID MonthName MonthlySales
Salesman A Feb 200.0000
Salesman A Jan 100.0000
Salesman A Mar 300.0000
Salesman B Feb 500.0000
Salesman B Jan 400.0000
Salesman B Mar 600.0000

There are (at least) two ways to do this, with potentially significant differences in execution plan and performance. I'm sure someone like Naomi can write these in her sleep, but anyone want to take a crack? I use this one as an example in SQL sessions to demonstrate a language feature added in SQL 2005 that doesn't always get as much attention as it should.
Next
Reply
Map
View

Click here to load this message in the networking platform