我有一个类似于以下的表(使用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
请注意,primaryid和caseid不是唯一的密钥标识符,值或多或少是随机的,仅用于演示我的数据的性质。我有兴趣知道我是否可以查询此数据以获得如下结果?:
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
非常感谢任何帮助。上面的表是一百万个连接的结果:)最后我很难过。
答案 0 :(得分:3)
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