TABLE1 TABLE2
ID DATE ID NAME
1 1 JAN 1 ABC
2 2 JAN 2 ABC
3 3 JAN 3 CDF
4 4 JAN 4 CDF
对表2进行分组,以使id = 1,2和3,4组成2个组,因为1,2具有NAME作为ABC,依此类推。这2个ID = 1,2和3,4的集合将与TABLE1结合在一起,其中TABLE以ID为ID,以在ID = 1,2和ID = 3,4之间搜索最小日期 这样最终结果应该像这样:
ID DATE
1 1 JAN
3 3 JAN
答案 0 :(得分:0)
一种使用ROW_NUMBER
的方式:
WITH cte AS (
SELECT t1.ID, t1.DATE,
ROW_NUMBER() OVER (PARTITION BY t2.NAME ORDER BY t2.ID) rn
FROM TABLE1 t1
INNER JOIN TABLE2 t2
ON t1.ID = t2.ID
)
SELECT ID, DATE
FROM cte
WHERE rn = 1;
答案 1 :(得分:0)
您可以简单地使用
select t1.id,t1.date from
table1 t1 join
(select min(ID) as id,name from
table2
group by name
) t2
on t1.id=t2.id
答案 2 :(得分:0)
通常,您可以使用join
和group by
来做到这一点:
select t2.name, min(t2.date)
from table1 t1 join
table2 t2
on t1.id = t2.id
group by t2.name;
这样的查询既不需要子查询,也不需要CTE。
答案 3 :(得分:0)
您希望每个名称一个结果行,因此请按名称分组:
select
min(t2.id) as id,
min(t1.date) as date
from table1 t1
join table2 t2 on t2.id = t1.id
group by t2.name
order by min(t2.id);
答案 4 :(得分:0)
select id, date
from table1
where dt in (select min(date)
from table1 A
left join table2 B
on A.id = B.id
group by name)