如何使用sql查询达到以下要求

时间:2019-01-04 11:27:37

标签: sql stored-procedures

  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

enter image description here

5 个答案:

答案 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)

通常,您可以使用joingroup 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)

db-fiddle

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)