有几种不同的方法可以将行转换为列。一种方法是使用带有 CASE 表达式的聚合函数:
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;
请参阅带有演示的 SQL Fiddle
或者由于您使用的是 SQL Server 2005+,您可以使用 PIVOT 函数:
select ApproachStatus, [GI Med Onc],[Breast Med Onc]
from yt
pivot
(
count(Clinic)
for Clinic in ([GI Med Onc],[Breast Med Onc])
) piv;
请参阅SQL Fiddle with Demo。
如果您有未知Clinic
值,那么您将需要查看使用动态 SQL 来获得结果:
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)
请参阅SQL Fiddle with Demo。所有查询都会给出结果:
| APPROACHSTATUS | GI MED ONC | BREAST MED ONC |
------------------------------------------------
| Approached | 2 | 1 |
| Not Approached | 0 | 1 |
| Pending | 1 | 0 |