我想根据以下条件过滤我的数据
- 对于一个ID,如果一个部件在特定的Types
A
和B
下出现两次或两次以上,那么我想过滤该部件上的数据。
data
个
| ID | TYPE | PART |
|-----|------|------|
| 101 | A | 10 |
| 101 | B | 10 |
| 101 | B | 10 |
| 101 | B | 20 |
| 101 | C | 30 |
| 102 | A | 10 |
| 102 | B | 25 |
| 103 | A | 25 |
| 103 | B | 25 |
字符串output
个
| ID | Type | Part |
|-----|------|------|
| 101 | A | 10 |
| 101 | B | 10 |
| 101 | B | 10 |
| 103 | A | 25 |
| 103 | B | 25 |
WITH data AS (
SELECT 101 id, 'A' type, 10 part FROM dual UNION ALL
SELECT 101 id, 'B' type, 10 part FROM dual UNION ALL
SELECT 101 id, 'B' type, 10 part FROM dual UNION ALL
SELECT 101 id, 'B' type, 20 part FROM dual UNION ALL
SELECT 101 id, 'C' type, 30 part FROM dual UNION ALL
SELECT 102 id, 'A' type, 10 part FROM dual UNION ALL
SELECT 102 id, 'B' type, 25 part FROM dual UNION ALL
SELECT 103 id, 'A' type, 25 part FROM dual UNION ALL
SELECT 103 id, 'B' type, 25 part FROM dual
)
SELECT * FROM data;
的数据another solution
个
WITH data AS (
SELECT 101 id, 'A' type, 10 part FROM dual UNION ALL
SELECT 101 id, 'B' type, 10 part FROM dual UNION ALL
SELECT 101 id, 'B' type, 10 part FROM dual UNION ALL
SELECT 101 id, 'B' type, 20 part FROM dual UNION ALL
SELECT 101 id, 'C' type, 30 part FROM dual UNION ALL
SELECT 102 id, 'A' type, 10 part FROM dual UNION ALL
SELECT 102 id, 'B' type, 25 part FROM dual UNION ALL
SELECT 103 id, 'A' type, 25 part FROM dual UNION ALL
SELECT 103 id, 'B' type, 25 part FROM dual UNION ALL
SELECT 104 id, 'C' type, 30 part FROM dual UNION ALL
SELECT 104 id, 'D' type, 30 part FROM dual
), data2 AS (
SELECT data.*, COUNT(DISTINCT type) OVER (PARTITION BY id, part) cnt
FROM data
WHERE type IN ('A','B')
)
SELECT id, type, part
FROM data2
WHERE cnt > 1;
型
3条答案
按热度按时间yhqotfr81#
试试这个(我在这里修复了104/103记录,假设与您的初始数据匹配)
字符串
pkbketx92#
这样应该就行了
字符串
o3imoua43#
只是为了多样化,因为通常有很多方法来解决一个问题。这是一个使用分析的解决方案。(我并不是说这比其他人表现得更好或更差。为此,请测试/验证和基准;))
但它确实给予了另一种选择。
字符串