Select只有一行按更多条件
Select only one row by more conditions
此查询受 PostgreSQL 支持,但 H2 无法运行查询,因为 Over(partition by) 。问题是如何 select 只有一行具有 2 列中不同值的最新创建时间。
Example:
id name created ecid psid
1 aa 2019-02-07 1 1
2 bb 2019-02-01 1 1
3 cc 2019-02-05 2 2
4 dd 2019-02-06 2 3
5 ee 2019-02-08 2 3
Result:
id name created ecid psid
1 aa 2019-02-07 1 1
3 cc 2019-02-05 2 2
5 ee 2019-02-08 2 3
SELECT s.*, MAX(s.created) OVER (PARTITION BY s.ecid, s.psid) AS latest FROM ...
WHERE latest = created
使用相关子查询
select t1.* from table t1
where t1.created = ( select max(created)
from table t2 where t1.ecid=t2.ecid and t1.psid=t2.psid)
使用NOT EXISTS
:
select t.* from tablename t
where not exists (
select 1 from tablename
where ecid = t.ecid and psid = t.psid and created > t.created
)
此查询受 PostgreSQL 支持,但 H2 无法运行查询,因为 Over(partition by) 。问题是如何 select 只有一行具有 2 列中不同值的最新创建时间。
Example:
id name created ecid psid
1 aa 2019-02-07 1 1
2 bb 2019-02-01 1 1
3 cc 2019-02-05 2 2
4 dd 2019-02-06 2 3
5 ee 2019-02-08 2 3
Result:
id name created ecid psid
1 aa 2019-02-07 1 1
3 cc 2019-02-05 2 2
5 ee 2019-02-08 2 3
SELECT s.*, MAX(s.created) OVER (PARTITION BY s.ecid, s.psid) AS latest FROM ...
WHERE latest = created
使用相关子查询
select t1.* from table t1
where t1.created = ( select max(created)
from table t2 where t1.ecid=t2.ecid and t1.psid=t2.psid)
使用NOT EXISTS
:
select t.* from tablename t
where not exists (
select 1 from tablename
where ecid = t.ecid and psid = t.psid and created > t.created
)