繁体   English   中英

SQL查询可获取外键内处于特定状态的所有记录

[英]SQL query to get all records in a certain status within a foreign key

我有一个很大的表(10,000多个记录),看起来或多或少像这样:

| id | name  | contract_no | status |
|----|-------|-------------|--------|
| 1  | name1 | 1022        | A      |
| 2  | name2 | 1856        | B      |
| 3  | name3 | 1322        | C      |
| 4  | name4 | 1322        | C      |
| 5  | name5 | 1322        | D      |

contract_no是一个外键,它当然可以出现在多个记录中,并且每个记录的状态均为A,B,C,D或E。

我想要的是获取所有合同编号的列表,其中引用该合同的所有记录都处于状态C,D,E或它们的混合状态,但是如果任何记录处于状态A或B,则省略该合同号。

是否可以使用SQL查询来做到这一点? 还是应该更好地导出数据并尝试使用其他语言(例如Python或R)运行此分析?

您可以使用group byhaving获取此类合同号。

select contract_number
from yourtable 
group by contract_number
having count(distinct case when status in ('C','D','E') then status end) >= 1
and count(case when status = 'A' then 1 end) = 0
and count(case when status = 'B' then 1 end) = 0

聚合后过滤应该可以解决问题

SELECT contract_no FROM t
GROUP BY contract_no
HAVING SUM(status='A')=0
AND SUM(status='B')=0

没有其他两个答案那么优雅,但是更具表现力:

SELECT DISTINCT contract_no
FROM the_table t1
WHERE NOT EXISTS (
    SELECT *
    FROM the_table t2
    WHERE t2.contract_no = t1.contract_no
    AND t2.status IN ('A', 'B')
)

要么

SELECT DISTINCT contract_no
FROM the_table
WHERE contract_no NOT IN (
    SELECT contract_no
    FROM the_table
    AND status IN ('A', 'B')
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM