我有T1
ID STATUS
1 NEW
2 NEW
我有T2
T1ID OWNER OWNDATE
1 A 01.01.2017 10:00:00
1 B 02.02.2017 10:00:00
1 C 03.03.2017 10:00:00
2 B 02.02.2017 10:00:00
2 C 03.03.2017 10:00:00
由于ID 1的A具有最小OWNDATE,因为ID 2的B具有最小OWNDATE
我想得到结果
1 NEW A
2 NEW B
但是在加入之后我不知道在哪里放MIN,所以我可以找到两个表中的最小值
SELECT
T1.ID, T1.STATUS, T2.OWNER
FROM
T1
JOIN
T2 ON T1.ID = T2.T1ID
提前谢谢
答案 0 :(得分:2)
以下是普通SQL中的解决方案,使用子查询,它应该适用于大多数数据库。
SELECT
T1.ID, T1.STATUS, T2.OWNER
FROM
T1
JOIN
T2
ON T1.ID = T2.T1ID
AND t2.owndate = (
select min( owndate ) FROM t2
where t2.T1ID = t1.id
)
答案 1 :(得分:1)
在大多数RDBMS中,您可以使用Windows分析功能
SELECT T1.ID,
T1.STATUS,
T.OWNER
FROM T1
INNER JOIN
(SELECT t2.*,
row_number() over(partition BY t1id
ORDER BY owndate) AS seq
FROM t2
) t
ON t1.id=t.t1id
AND t.seq=1
答案 2 :(得分:0)
select t1.*, t3.OWNER
from t1
inner join lateral
(
select * from t2
where t1.id=t2.T1ID
order by t2.OWNDATE
fetch first rows only
) t3 on 1=1