Vivekananda
Vivekananda

Reputation: 51

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) :

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. 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.

Upvotes: 0

Views: 61

Answers (1)

KrazzyNefarious
KrazzyNefarious

Reputation: 3230

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

Upvotes: 3

Related Questions