【发布时间】:2020-09-16 14:48:37
【问题描述】:
假设我有一个 table1:
column1|column2|state|
-------|-------|-----|
test1 | 2| 0|
test1 | 3| 0|
test1 | 1| 1|
test2 | 2| 1|
test2 | 1| 2|
我想选择(实际上是删除,但我使用 select 进行测试)所有不具有唯一 column1 的列,并且不选择(实际上保留)仅具有以下内容的行:
- state = 0 和 column2 中的最小值,
- 如果不存在 state = 0 的行,则 column2 中只有最小值的行。
所以如果选择应该是结果:
column1|column2|state|
-------|-------|-----|
test1 | 3| 0|
test1 | 1| 1|
test2 | 2| 1|
保留的行(在删除的情况下)应该是:
column1|column2|state|
-------|-------|-----|
test1 | 2| 0|
test2 | 1| 2|
我尝试通过以下方式实现它(这不起作用):
SELECT * FROM table1 AS result1
WHERE
result1.column1 IN
(SELECT
result2.column1
FROM
table1 AS result2
WHERE /*part that works*/)
AND
result1.column2 >
(SELECT
min(result3.column2)
FROM
table1 AS result3
WHERE (COALESCE(
result3.column1 = result1.column1
AND
result3.state = 0,
WHERE
result3.column1 = result1.column1
)))
我想不通的部分在result1.column2 >后面。
我想将result1.column2 与
-
it3.state = 0的结果集中的最小值, - 如果 1. 不存在,则在没有
it3.state = 0条件的类似结果集中具有最小值。
这是我的问题,我希望它有意义。也许它可以完全以更有效/更整洁的方式重写。
你能帮我解决这个问题吗?
【问题讨论】:
-
样本数据和所需结果比不工作的查询更有帮助。
-
@GordonLinoff 好的,正在添加。
标签: sql postgresql coalesce