簡體   English   中英

在 Oracle SQL 中,如何找到一列中的所有值,而另一列中存在多個不同值

[英]In Oracle SQL how can i find all values in one column for which in another column exist more than one distinct value

我有一個像這樣的 Oracle 表

| id | code | info             | More cols |
|----|------|------------------|-----------|
| 1  | 13   | The Thirteen     | dggf      |
| 1  | 18   | The Eighteen     | ghdgffg   |
| 1  | 18   | The Eighteen     |           |
| 1  | 9    | The Nine         | ghdfgjgf  |
| 1  | 9    | Die Neun         | ghdfgjgf  |
| 1  | 75   | The Seventy-five | ghfgh     |
| 1  | 75   | The Seventy-five | ghfgh     |
| 1  | 2    | The Two          | ghfgh     |
| 1  | 27   | The Twenty-Seven |           |
| 1  | 27   | The Twenty-Seven |           |
| 1  | 27   | el  veintisiete  | fghfg     |
| .  | .    | .                | .         |
| .  | .    | .                | .         |
| .  | .    | .                | .         |

在此表中,我想查找列code中具有值的所有行,這些行在info列中具有多個不同的 因此,從列出的行中,這將是值927以及相關的行。

我試圖構建第一個查詢,如

SELECT code FROM mytable
  WHERE COUNT(DISTINCT info) >1

但我收到“ ORA-00934:此處不允許使用組功能”錯誤。 另外我不知道如何表達條件COUNT(DISTINCT info) "with a fixed postcode"

您需要havinggroup by - aggregate functions不工作where clause

SELECT code 
       FROM mytable
group by code
having COUNT(DISTINCT info) >1

我會將您的查詢寫為:

SELECT code
FROM yourTable
GROUP BY code
HAVING MIN(info) <> MAX(info);

以這種方式編寫HAVING邏輯會使查詢sargable ,這意味着(code, info)上的索引應該可用。

你也可以使用存在邏輯來做到這一點:

SELECT DISTINCT code
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable WHERE t2.code = t1.code AND t2.info <> t1.info);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM