SQL:获取具有两个突变的数据计数

时间:2019-03-23 21:30:20

标签: sql sql-server sql-server-2017

我有2个表MutationsMedications

我需要在医学名称中同时拥有mut1和mut2的那些成员的数量

SELECT 
    med.Name AS medicine, COUNT(*) AS count
FROM 
    Mutations mut
INNER JOIN 
    Medications med ON med.MemberId = mut.MemberId
WHERE 
    mut.Mutation IN ('mut1','mut2')
GROUP BY 
    med.Name
HAVING 
    COUNT(DISTINCT mut.Mutation) = 2

如何获取同时具有突变的成员的计数?

2 个答案:

答案 0 :(得分:1)

一种方法是两种聚合级别:

select med.name, count(*)
from (select med.name, m.memberid
      from medications med join
           mutations m
           on m.memberid = med.memberid
      where m.mutation in ('mut1', 'mut2')
      group by med.name, m.memberid
      having count(*) = 2
     ) m
group by med.name;

答案 1 :(得分:0)

目前尚不清楚您需要什么计数,您的查询实际上是在获取具有两种突变的药物...

如果您希望对给定查询进行计数,请使用子查询

SELECT 
    med.Name AS medicine, 
    COUNT(CASE Mutation WHEN 'Mut1' THEN 1 END) AS CountMut1
    COUNT(CASE Mutation WHEN 'Mut2' THEN 1 END) AS CountMut2
FROM 
    Mutations mut
INNER JOIN 
    Medications med ON med.MemberId = mut.MemberId
WHERE 
    mut.Mutation IN ('mut1','mut2')
GROUP BY 
    med.Name
HAVING 
    COUNT(DISTINCT mut.Mutation) = 2

如果您想将Mut1和mut2用例的数量分开

JSON.parse