我有一张这样的表:
ID Diagnosis
---------------
1 d1
1 d2
1 d3
2 d1
2 d3
2 d4
3 d1
3 d2
我想计算同时包含ID
和d1
的唯一d2
。
所需的输出像这样
total
------
2
如何编写SQL代码来实现这一目标?
答案 0 :(得分:2)
您可以使用几个in
条件:
SELECT COUNT(DISTINCT id)
FROM my_table
WHERE id IN (SELECT id FROM my_table WHERE diagnosis = 'id1') AND
id IN (SELECT id FROM my_table WHERE diagnosis = 'id2')
答案 1 :(得分:2)
这是MySQL的解决方案......
SELECT x.id
FROM my_table x
WHERE diagnosis IN ('d1','d2')
GROUP
BY id
HAVING COUNT(*) =2;
+----+
| id |
+----+
| 1 |
| 3 |
+----+
2 rows in set (0.00 sec) <-- ANSWER!!!
答案 2 :(得分:0)
这可能会有所帮助..我已经更新了..
select count(*) as TOTAL from TABLE_NAME where Diagnosis in ('d1', 'd2') group by Diagnosis
答案 3 :(得分:0)
你已经非常模糊地写了你的问题,但我认为你想要在MSSQL下面的解决方案:
select COUNT(1) from
(
select distinct(id) from my_table where Diagnosis = 'd1'
intersect
select distinct(id) from my_table where Diagnosis = 'd2'
) as TempResultset
如果单独运行内部查询,您将获得ID。