简体   繁体   English

具有SQL Server 2008 R2中的值计数的交叉表查询

[英]Crosstab query with count of values in SQL Server 2008 R2

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! 我玩过修改我在这里找到的代码,但是......任何帮助都表示赞赏!

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: 一种方法是使用带有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;

See SQL Fiddle with Demo 请参阅SQL Fiddle with Demo

Or since you are using SQL Server 2005+, you can use the PIVOT function: 或者,由于您使用的是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;

See SQL Fiddle with Demo . 请参阅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: 如果您有一个未知的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)

See SQL Fiddle with Demo . 请参阅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 |

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM