我在查找正确的SQL(oracle)查询时遇到了问题(可能是nooby问题):
我有这个已经是联接表的表
---------------------
|PersonID | NumberA | Group |
-------------------------
| 1 | 111 | 02 |
-------------------------
| 2 | 222 | 02 |
-------------------------
| 3 | 467 | 02 |
-------------------------
| 1 | 122 | 01 |
-------------------------
| 5 | 048 | 01 |
-------------------------
| 5 | 491 | 01 |
现在我想让所有在组列中具有至少一行具有值'02'并且在组列中具有至少一行具有值'01'的人。
我无法提出一种如何正确查询此问题的解决方案。
有人可以帮助我吗?
答案 0 :(得分:2)
我建议使用group by
和having
:
select personID
from t
where groupId in ('01', '02')
group by personID
having min(groupId) = '01' and max(groupId) = '02';
答案 1 :(得分:2)
您可以同时使用WHERE
和COUNT(DISTINCT ...)
:
SELECT "PersonID"
FROM your_table
WHERE "Group" IN ('01', '02')
GROUP BY "PersonID"
HAVING COUNT(DISTINCT "Group") = 2
如果您要精确地查找 x个具有一定值的行,则将hading子句更改为类似的内容:
HAVING COUNT(CASE WHEN "Group" = '01' THEN 1 END) = 2
AND COUNT(CASE WHEN "Group" = '02' THEN 1 END) = 3
答案 2 :(得分:1)
将JOINED
表结果视为单个表,则可以使用exists
:
select t.*
from table t
where group ('01', '02') and
exists (select 1 from table t1 where t1.personid = t.personid and t1.group <> t.group);
答案 3 :(得分:0)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="table">
</div>
<script src="script.js"></script>
</body>
</html>