我的数据库中有 Pruza 表,该表中的情况例如:
SifVU Name
1 Test1
2 Test2
1 Test3
2 Test3
如何进行仅返回 Test3 作为结果的 Select 查询,因为只有 Test3 同时具有 Sif(1 和 2)。
试试这个,它只显示具有 SifVU 1 和 2 的名称:
select one.name
from (select name from Pruza where SifVU = 1) one
join (select name from Pruza where SifVU = 2) two
on (one.name = two.name)
SELECT Name
FROM Pruza
WHERE SifVU in (1,2)
GROUP BY Name
HAVING COUNT(DISTINCT SifVU) = 2
见小提琴。
这可用于任意数量的 TEST3 类型的记录,无需任何硬编码
SELECT B.NAME
FROM
(SELECT COUNT(SifVU) AS CNT_SifVU FROM TABLE GROUP BY SifVU) AS A
INNER JOIN
(
SELECT COUNT(*) AS DISTINCT_SIFVU, NAME
FROM
(SELECT DISTINCT SifVU, Name FROM TABLE) AS B
) AS C
ON B.DISTINCT_SIFVU = A.CNT_SifVU