【问题标题】:Group by column with preference for rows in which another column is not null按列分组,优先选择另一列不为空的行
【发布时间】:2020-10-01 17:20:52
【问题描述】:

假设我有一个看起来像这样的表,有两个外键:

| col1 | fkey1 | fkey2 |
|------|-------|-------|
| foo  | 123   | null  |
| foo  | 123   | 456   |
| bar  | 789   | null  |

我将如何按col1 分组,优先选择fkey2 不是 null 所在的行?所以结果看起来像这样:

| col1 | fkey1 | fkey2 |
|------|-------|-------|
| foo  | 123   | 456   |
| bar  | 789   | null  |

另一个考虑因素是fkey1 有一个not null 约束,而fkey2 没有。

【问题讨论】:

  • fkey2 是否定义为 UNIQUE?如果不是,从具有不同非空值的同行中选择哪一行?会涉及更多的列吗?使用显示数据类型和约束的CREATE TABLE 语句,这个问题会更有用。

标签: sql postgresql select greatest-n-per-group sql-null


【解决方案1】:

对于这个数据集,您可以使用简单的聚合:

select col1, fkey1, max(fkey2) fkey2
from mytable
group by col1, fkey1

但我怀疑你实际上想要distinct on

select distinct on(col1) t.*
from mytable t
order by col1, fkey2

【讨论】:

    猜你喜欢
    • 2017-01-22
    • 2019-02-18
    • 2017-04-26
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    相关资源
    最近更新 更多