Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SQL Pivot

Posted on 2013-05-21
5
Medium Priority
?
358 Views
Last Modified: 2013-05-21
How can I do a select on a Specialties table and a states table

Specialties table has
SpecialtyID     StateID


States table has
StateID     StateName (Varchar(2))

So that I have this output

SpecialtyID   AK               AL   AZ   etc....
data              count(AK)   etc...
0
Comment
Question by:lrbrister
  • 3
  • 2
5 Comments
 
LVL 41

Assisted Solution

by:Sharath
Sharath earned 2000 total points
ID: 39185296
try this
select *
  from (
		select s1.SpecialtyID,s2.StateName
		  from Specialties s1
		  join States s2 on s1.StateID = s2.StateID) t1
 pivot (count(StateName) for StateName in ([AK],[AL],[AZ])) p		  

Open in new window


http://sqlfiddle.com/#!3/75dc7/1
0
 
LVL 41

Accepted Solution

by:
Sharath earned 2000 total points
ID: 39185324
You can do it dynamically if you have lot of states.
 
 declare @select varchar(max)
select @select = STUFF((select distinct ',' + quotename(StateName, '')
from States
for XML PATH('')
),1,1,'' )

select @select = 'select *
  from (
		select s1.SpecialtyID,s2.StateName
		  from Specialties s1
		  join States s2 on s1.StateID = s2.StateID) t1
 pivot (count(StateName) for StateName in ('+@select+')) p'
 exec(@select)

Open in new window


 http://sqlfiddle.com/#!3/e12ec/1
0
 

Author Closing Comment

by:lrbrister
ID: 39185477
Great answers
Watch for follow-up.  I messed this question up actually
0
 
LVL 41

Expert Comment

by:Sharath
ID: 39185584
post your follow-up question
0

Featured Post

Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how the fundamental information of how to create a table.

886 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question