我需要从表中保存每名组一行一个最大值:获取每
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),并且如果这不是结果一行 - 带有最大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
我试图做到这一点与嵌套的连接,但似乎过于复杂。 一些简单的解决方法是先做SQL结果ORDER BY的:
CREATE TABLE output AS
SELECT
ID,
Name,
Attribute1,
Attribute2,
Attribute3
FROM input
ORDER BY
Name,
Attribute1 DESC,
Attribute2 DESC,
Attribute3 DESC;
,做每一行的循环,并检查和缓存,如果名字之前发生 - 如果不是,保护它(和缓存名字在一些全球变量),否则删除行。
有没有其他纯粹的SQL解决方案?
“*在第一位应该真正在ATTRIBUTE1 *保存行” - 违背你的期望的结果,因为有一排'ATTRIBUTE1 = FALSE ' –
@a_horse_with_no_name我开始使用sqlite,因为我需要快速解决方案而无需安装postgresql - 但最终它可能是任何数据库。它不能为attribute1 = true,因为如果组中的所有行在Attribute1上都有false,还是需要从组中拾取某些内容 - 但是基于Attribute2和Attribute3。 – erhesto
您需要决定使用的DBMS。根据数据库引擎的功能,这种查询将会非常不同。 –