• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

Pivot question

Trying to use the pivot function which may not be the right function to use anyways but here is the issue.

I have the following result set.


Amb_no        season_desc        event_no

1                    A                           100
1                    A                           101
2                    A                           100
3                    A                           100
3                    A                           101
3                    A                           102
1                    B                           103
1                    B                           104
2                    B                           103
3                    B                           103
3                    B                           104
3                    B                           105


What I am looking for in the end result is:

Amb_no        A        B      
1                   2        2 <count(event_no)>
2                   1        1
3                   3        3


The trick is that the number distinct season_desc may change. one time I may have only 2 and the next time I may have 5. In this case my column header would look like


Amb_no        A        B        C         D        E


Thanks for the help.  
0
DowntownIT
Asked:
DowntownIT
  • 2
  • 2
1 Solution
 
ralmadaCommented:
try
select Amb_no, [A], [B], [C], [D], [E]
from 	(
	select Amb_no, season_desc, event_no from yourtable
	) o
pivot (count(event_no) for season_desc in ([A], [B], [C], [D], [E])) as p

Open in new window

0
 
DowntownITAuthor Commented:
My only issue with this approach is that I don't not know what the values of season_desc are going to be. One user may select only A and B and the next user may select C, D, and E. So I am not able to hard code the season_desc column values into the procedure. It is this reason that I am thinking that Pivot won't work for me.

Thanks,
0
 
ralmadaCommented:
in that case you can do it dynamically, check the below:


declare @strSQL varchar(max)
declare @cols varchar(max)

set @cols = stuff((select distinct  '], [' + season_desc 
			from yourtable order by 1 for xml path('')), 1, 2, '') + ']'



set @strSQL = 'select Amb_no, ' + @cols + ' from (
		select Amb_no, season_desc, event_no from yourtable) o
		pivot (count(event_no) for season_desc in (' + @cols + ')) as p'

exec(@strSQL)

Open in new window

0
 
DowntownITAuthor Commented:
Worked Brilliantly!!

Thank you so much for the help.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now