다음 tbl
과 같은 테이블 이 있습니다.
| id | grp | pid | oid |
| -- | --- | --- | --- |
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 1 |
| 3 | 3 | 1 | 1 |
| 4 | 3 | 2 | 1 |
| 5 | 4 | 1 | 1 |
| 6 | 1 | 1 | 2 |
| 7 | 2 | 2 | 2 |
| 8 | 3 | 1 | 2 |
| 9 | 4 | 1 | 2 |
주어진 OID에서 주어진 GRP에 대해 PID가 1보다 큰 고유 카운트를 갖는 행을 선택하는 PostgreSQL 쿼리를 작성하려고합니다. OID 1, 다음을 반환해야합니다.
| id | grp | pid | oid |
| -- | --- | --- | --- |
| 3 | 3 | 1 | 1 |
| 4 | 3 | 2 | 1 |
Python + Pandas를 사용하여 이에 대한 해결책이 있지만 이상적이지 않습니다.
import pandas as pd
rows = pd.read_sql("SELECT * FROM tbl", db.engine)
output = pd.DataFrame(columns = rows.columns)
oids = rows['oid'].tolist()
for oid in oids:
oid_rows = rows[rows['oid'] == oid]
grps = oid_rows['grp'].tolist()
for grp in grps:
grp_rows = oid_rows[oid_rows['grp'] == grp]
if len(grp_rows) > 1:
output = pd.concat([output, grp_rows],axis=0)
print(output)
나는 순전히 SQL로, 본질적으로 다음과 같은 쿼리를 선호합니다.
SELECT * FROM tbl HAVING COUNT(pid) > 1 IN
(SELECT * FROM tbl GROUP BY grp, oid)
이 쿼리를 어떻게 작성합니까?
다음을 사용할 수 있습니다 exists
.
select t.*
from tbl t
where exists (select 1
from tbl t2
where t2.grp = t.grp and t2.oid = t.oid and
t2.id <> t.id
);
창 기능을 사용할 수도 있습니다.
select t.*
from (select t.*, count(*) over (partition by grp, oid) as cnt
from tbl t
) t
where cnt >= 2;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다