【问题标题】:PostgreSQL - Count and Case combinedPostgreSQL - 计数和大小写相结合
【发布时间】:2018-08-13 09:33:20
【问题描述】:

我有以下 SQL 语句:

SELECT sk.kontonummer as Sachkonto, 
CASE WHEN COUNT(*) > 2 ktr.kostentraeger_nr + ' 
 and more' 
ELSE ktr.kostentraeger_nr END,
 (...) 

因此,我可以获得 2 行或更多行。 当我得到 3 行或更多行时,我想在 "ktr.kostentraeger_nr" 'and more' (作为字符串)之后写在后面,如果不是那么只有结果本身。

由于计数功能,查询本身不可执行 - 粗体文本只是我认为它应该如何工作的想法。 有什么方法可以满足我的要求吗?

为了阐明我的要求,举个例子:

非常感谢,我已经因为这个问题浪费了一整天...

【问题讨论】:

标签: postgresql case aggregate-functions


【解决方案1】:

您只需要使用OVER()。不知道您的查询或数据库结构,但这里有一个简单的示例,应该会有所帮助。

让我们有一个表测试喜欢

id | integer_value | text_value
---+---------------+------------
1  | 5             | a
2  | 7             | b
3  | 8             | c
4  | 1             | d

为了得到实际查询的COUNT,我们使用窗口函数OVER()

SELECT id,integer_value
    CASE
-- since you have to add text, the integer must be cast as text.
        WHEN COUNT(*) OVER () > 2 THEN integer_value::text||' and more'
        ELSE integer_value::text
    END AS altered_integer,
    text_value
-- To test you can change the condition. When lower than 3, it shows just the value,
-- if you change the query and set lower than 4, the column will have 'and more'.
FROM instituciones WHERE id<3
--FROM instituciones WHERE id<4

id

id | integer_value | altered_integer | text_value
---+---------------+-----------------+------------
1  | 5             | 5               | a
2  | 7             | 7               | b

id

id | integer_value | altered_integer | text_value
---+---------------+-----------------+------------
1  | 5             | 5 and more      | a
2  | 7             | 7 and more      | b
3  | 8             | 8 and more      | c

当使用OVER() 时,您对COUNT 函数说它必须对整个查询行进行计数。

注意:如果查询没有任何条件,OVER() 将返回整个表的计数

【讨论】:

  • 谢谢!解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多