简体   繁体   English

查询以将同一列中两行的值分组并显示计数

[英]Query to group values from two rows in the same column and display count

I have a table similar to the following (using sql-server 2012) : 我有一个类似于以下表格(使用sql-server 2012):

primaryid     Caseid     Indication   Reaction        Drugname
1             2          Pain         Vomiting        DrugA
1             2          Pain         Vomiting        DrugB
3             4          Pain         Headache        DrugA
3             4          Pain         Headache        DrugB
16            17         Pain         Sleepiness      DrugC
16            17         Pain         Sleepiness      DrugD
16            18         Pain         Sleepiness      DrugC
16            18         Pain         Sleepiness      DrugD

Please note that primaryid and caseid are NOT unique key identifiers and the values are more or less random, just used to demonstrate the nature of my data. 请注意,primaryid和caseid不是唯一的键标识符,并且值或多或少是随机的,仅用于演示我的数据的性质。 I am interested in knowing if I can query this data to achieve result like the following?: 我想知道是否可以查询此数据以达到如下结果?

primaryid     Caseid     Indication   Reaction        Drugname        Count
1             2          Pain         Vomiting        DrugA, DrugB     2
3             4          Pain         Headache        DrugA, DrugB     2 
16            17         Pain         Sleepiness      DrugC, DrugD     2
16            18         Pain         Sleepiness      DrugC, DrugD     2

Any help would be greatly appreciated. 任何帮助将不胜感激。 The table above itself is a result of a million joins:) and finally I am stumped at this point. 上表本身是一百万个联接的结果:)最后,我在这一点上感到困惑。

declare @table table (primaryid int, caseid int, indication varchar(10), reaction varchar(10), drugname varchar(10))

insert into @table values (1,2 ,'Pain','Vomiting','DrugA')
insert into @table values (1, 2,'Pain','Vomiting','DrugB')
insert into @table values (3,4,'Pain','Headache','DrugA')
insert into @table values (3,4,'Pain','Headache','DrugB')
insert into @table values (16,17,'Pain','Sleepiness','DrugC')
insert into @table values (16,17,'Pain','Sleepiness','DrugD')
insert into @table values (16,18,'Pain','Sleepiness','DrugC')
insert into @table values (16,18,'Pain','Sleepiness','DrugD')

SELECT
    G.primaryid,
    G.caseid,
    G.indication,
    g.reaction,
    stuff(
    (
    select cast(',' as varchar(max)) + U.drugname
    from @table U
    WHERE U.primaryid = G.primaryid
    and u.caseid = g.caseid
    and u.indication = g.indication
    and u.reaction = g.reaction
    order by U.primaryid
    for xml path('')
    ), 1, 1, '') AS drugname,
    count(*) Count
FROM
    @table G
    group by G.primaryid,
    G.caseid,
    G.indication,
    g.reaction

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

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