问题
I've searched and am not finding (or understanding!) how to do what I need to do. I feel a bit silly asking this since there are other examples, but I'm just not getting it....
Here's the data I have in a view:
[Approach Status] [Clinic]
Approached GI Med Onc
Pending GI Med Onc
Approached GI Med Onc
Not Approached Breast Med Onc
Approached Breast Med Onc
What I need is:
[Approach Status] [GI Med Onc] [Breast Med Onc]
Approached 2 1
Not Approached 0 1
Pending 1 0
I've played with modifying code I found on here but.... any help is appreciated!
回答1:
There are a few different ways that you can convert the rows to columns. One way that you can do this is by using an aggregate function with a CASE expression:
select ApproachStatus,
sum(case when Clinic = 'GI Med Onc' then 1 else 0 end) [GI Med Onc],
sum(case when Clinic = 'Breast Med Onc' then 1 else 0 end) [Breast Med Onc]
from yt
group by ApproachStatus;
See SQL Fiddle with Demo
Or since you are using SQL Server 2005+, you can use the PIVOT function:
select ApproachStatus, [GI Med Onc],[Breast Med Onc]
from yt
pivot
(
count(Clinic)
for Clinic in ([GI Med Onc],[Breast Med Onc])
) piv;
See SQL Fiddle with Demo.
If you have an unknown Clinic values, then you will need to look at using dynamic SQL to get the result:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Clinic)
from yt
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ApproachStatus,' + @cols + '
from yt
pivot
(
count(Clinic)
for Clinic in (' + @cols + ')
) p '
execute(@query)
See SQL Fiddle with Demo. All queries will give a result:
| APPROACHSTATUS | GI MED ONC | BREAST MED ONC |
------------------------------------------------
| Approached | 2 | 1 |
| Not Approached | 0 | 1 |
| Pending | 1 | 0 |
来源:https://stackoverflow.com/questions/16946836/crosstab-query-with-count-of-values-in-sql-server-2008-r2