在 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 table
| 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 |
| . | . | . | . |
| . | . | . | . |
| . | . | . | . |
在此 table 中,我想查找列 code
中具有值的所有行,这些行具有 多个 distinct 值 在 info
列中。因此,从列出的行中,这将是值 9
和 27
以及关联的行。
我尝试构造第一个查询,例如
SELECT code FROM mytable
WHERE COUNT(DISTINCT info) >1
但我收到“ORA-00934:此处不允许组函数”错误。我也不知道如何表达条件 COUNT(DISTINCT info)
"with a fixed postcode".
您需要 having
和 group 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
逻辑会使查询 可搜索 ,这意味着 (code, info)
上的索引应该可用。
您也可以使用现有逻辑执行此操作:
SELECT DISTINCT code
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable WHERE t2.code = t1.code AND t2.info <> t1.info);
我有一个这样的 Oracle table
| 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 |
| . | . | . | . |
| . | . | . | . |
| . | . | . | . |
在此 table 中,我想查找列 code
中具有值的所有行,这些行具有 多个 distinct 值 在 info
列中。因此,从列出的行中,这将是值 9
和 27
以及关联的行。
我尝试构造第一个查询,例如
SELECT code FROM mytable
WHERE COUNT(DISTINCT info) >1
但我收到“ORA-00934:此处不允许组函数”错误。我也不知道如何表达条件 COUNT(DISTINCT info)
"with a fixed postcode".
您需要 having
和 group 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
逻辑会使查询 可搜索 ,这意味着 (code, info)
上的索引应该可用。
您也可以使用现有逻辑执行此操作:
SELECT DISTINCT code
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable WHERE t2.code = t1.code AND t2.info <> t1.info);