【问题标题】:Get one maximum value per group每组获取一个最大值
【发布时间】:2017-04-19 13:43:09
【问题描述】:

我需要为表中的每组名称保留一行:

ID | Name  | Attribute1| Attribute2 | Attribute3
 1 | john  | true      | 2012-20-10 | 12345670
 2 | john  | false     | 2015-20-10 | 12345671
 3 | james | false     | 2010-02-01 | 12345672
 4 | james | false     | 2010-02-03 | 12345673
 5 | james | false     | 2010-02-06 | 12345674
 6 | sara  | true      | 2011-02-02 | 12345675
 7 | sara  | true      | 2011-02-02 | 12345676

...根据指定的标准。首先应该保留 Attribute1 中具有 true 的行(如果存在),然后保留最大日期(Attribute2),如果这不是一行 - 具有最大 Attribute3 的行。

想要的结果是:

ID|Name|Attribute1|Attribute2|Attribute3
1 | john  | true  | 2012-20-10 | 12345670
5 | james | false | 2010-02-06 | 12345674
7 | sara  | true  | 2011-02-02 | 12345676

我尝试使用嵌套连接来做到这一点,但这似乎过于复杂。 一些简单的解决方案是首先执行 ORDER BY 的 SQL 结果:

CREATE TABLE output AS
SELECT 
    ID, 
    Name,
    Attribute1,
    Attribute2,
    Attribute3
FROM input 
ORDER BY 
    Name,
    Attribute1 DESC, 
    Attribute2 DESC, 
    Attribute3 DESC;

并为每一行执行循环并检查并缓存名称是否之前出现 - 如果没有,则保留它(并将名称缓存在某个全局变量中),否则删除行。

还有其他纯SQL解决方案吗?

【问题讨论】:

  • "首先应该保留 Attribute1 中为 true 的行" - 这与您想要的结果相矛盾,因为有一行 attribute1 = false
  • @a_horse_with_no_name 我从 sqlite 开始,因为我需要快速解决方案而无需安装 postgresql - 但最终,它可能是任何数据库。它不能是 attribute1 = true,因为如果 group 中的所有行在 Attribute1 上都为 false,仍然需要从 group 中提取一些东西 - 但基于 Attribute2 和 Attribute3。
  • 您需要决定您使用的 DBMS。这种查询会根据数据库引擎的特性有很大的不同

标签: sql postgresql sqlite


【解决方案1】:

对于 Postgresql:

select distinct on (name) *
from t
order by name, attribute1 desc, attribute2 desc, attribute3 desc

https://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT

【讨论】:

  • 非常感谢。简直难以置信,它在 postgres 中。
猜你喜欢
  • 1970-01-01
  • 2010-09-16
  • 1970-01-01
  • 2017-06-11
  • 2022-11-10
  • 2021-07-19
  • 2017-04-17
  • 2017-09-12
相关资源
最近更新 更多