Sql 每个组获得一个最大值

Sql 每个组获得一个最大值,sql,postgresql,sqlite,Sql,Postgresql,Sqlite,我需要为表中的每组名称保留一行: 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 | 12345

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

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的行(如果存在),然后是max date(Attribute2),如果不是这样,则应保留一行,即具有max 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的SQL结果:

CREATE TABLE output AS
SELECT 
    ID, 
    Name,
    Attribute1,
    Attribute2,
    Attribute3
FROM input 
ORDER BY 
    Name,
    Attribute1 DESC, 
    Attribute2 DESC, 
    Attribute3 DESC;
对每一行执行循环,检查并缓存之前是否出现过名称-如果没有,则保留它(并将名称缓存在某个全局变量中),否则删除行

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

对于Postgresql:

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

“首先应该在Attribute1中保留带有true的行”-这与您想要的结果相矛盾,因为有一行带有
Attribute1=false
@a_horse_和_no_名称我从sqlite开始,因为我需要快速解决方案,而不需要安装postgresql-但最终,它可能是任何数据库。它不能是attribute1=true,因为如果组中的所有行的attribute1都为false,则仍然需要从组中提取一些内容,但要基于Attribute2和Attribute3。您需要决定使用的DBMS。根据数据库引擎的特性,这种查询会有很大的不同。令人难以置信的是,它只是在深造。