【问题标题】:Something like COALESCE for complicated query?像 COALESCE 这样的复杂查询?
【发布时间】: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 的列,并且不选择(实际上保留)仅具有以下内容的行:

  1. state = 0 和 column2 中的最小值,
  2. 如果不存在 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

的结果进行比较
  1. it3.state = 0 的结果集中的最小值,
  2. 如果 1. 不存在,则在没有it3.state = 0 条件的类似结果集中具有最小值。

这是我的问题,我希望它有意义。也许它可以完全以更有效/更整洁的方式重写。
你能帮我解决这个问题吗?

【问题讨论】:

  • 样本数据和所需结果比不工作的查询更有帮助。
  • @GordonLinoff 好的,正在添加。

标签: sql postgresql coalesce


【解决方案1】:

这是你想要的吗?

SELECT
        *
  FROM
        table1 AS result1
 WHERE
        result1.column1 IN (SELECT result2.column1
                              FROM table1 AS result2
                             WHERE /*part that works*/)
   AND  result1.column2 > COALESCE( ( SELECT min(result3.column2)
                                        FROM table1 AS result3
                                       WHERE result3.column1 = result1.column1 
                                         AND result3.state = 0 )
                                   ,( SELECT min(result3.column2)
                                        FROM table1 AS result3
                                       WHERE result3.column1 = result1.column1  )
                                  )

;

【讨论】:

  • 不确定在这种情况下 it3 是什么,所以不得不做一些猜测。
  • 对不起,it3应该是result3,我混淆的时候搞砸了。
  • 有时你只需要第二双眼睛就能看到某样东西。
  • 我测试了一下,我想我之前有解决方案,但是没有括号,它会出现语法错误。
猜你喜欢
  • 1970-01-01
  • 2023-02-23
  • 2012-12-27
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多