连接两个表并查找最早的日期SQL

时间:2018-07-26 15:48:03

标签: sql date join sql-server-2012

我有以下两个表,我需要得到以下结果:

表1

(A, 1, 01/01/2015),
(A, 1, 10/01/2015),
(A, 2, 20/01/2015),
(A, 2, 01/05/2015),
(B, 1, 20/02/2014),
(B, 1, 20/02/2015),
(B, 2, 20/02/2016),
(B, 2, 06/05/2015)

表2

(A, 1, 123),
(A, 1, 123),
(A, 2, 234),
(A, 2, 234),
(B, 1, 123),
(B, 2, 123),

我想返回每个组合的最早日期:

(A, 123, 01/01/2015),
(A, 234, 20/01/2015),
(B, 123, 20/02/2014)

我尝试过的代码:

DECLARE @table1 TABLE (letter1 CHAR(1), num1 INT, date1 INT)  
DECLARE @table2 TABLE (letter1 CHAR(1), num1 INT, num2 INT)  

INSERT INTO @table1 VALUES    
    ('A', 1, 01012015),  
    ('A', 1, 10012015),  
    ('A', 2, 20012015),  
    ('A', 2, 01052015),  
    ('B', 1, 20022014),  
    ('B', 1, 20022015),  
    ('B', 2, 20022016),  
    ('B', 2, 06052015)  

INSERT INTO @table2 VALUES   
    ('A', 1, 123),  
    ('A', 1, 123),   
    ('A', 2, 234),  
    ('A', 2, 234),  
    ('B', 1, 123),  
    ('B', 2, 123)  



SELECT DISTINCT [@table1].letter1,  num2, MIN(date1) FROM @table1
INNER JOIN @table2 ON [@table1].letter1 = [@table2].letter1 AND [@table1].num1 = [@table2].num1
GROUP BY [@table1].letter1, [@table1].num1, num2

3 个答案:

答案 0 :(得分:1)

您可以使用select 'matched' where 'abc' like '%abc,def,ghi,jkl%' select 'matched' where 'abc,def,ghi,jkl' like '%abc%' 函数:

row_number()

答案 1 :(得分:0)

试试看。可以按日期在分组中添加date1 SELECT DISTINCT [@ table1] .letter1,num2,MIN(date1)来自@ table1内连接@ table2 ON [@ table1] .letter1 = [@ table2] .letter1和[@ table1] .num1 = [@ table2] .num1 GROUP BY [@ table1] .letter1,[@ table1] .num1,num2,date1

答案 2 :(得分:0)

;with cte as 
(
  select  name, IIF(c = 1, 0, id) id, value from    --- Here We separet the whole into two groups. 
 (
   select name, id, value, count(*) c from #table2 group by name, id, value 
 ) ct                                               ---- Here one group (B) has same value (123).
                                                    ---- And another group (A) have diff values (123,234))
)select c.name, c.value, min(t1.yyymmdd) from cte c
join #table1 t1 
on c.name = t1.name 
and c.id = t1.id                                    ------ Id's join must. Because it has two different ids 
and c.id <> 0                                       ------ 'A' group has been joined
group by c.name, value union 
select c.name, c.value, min(t1.yyymmdd) Earlier_date from cte c 
join #table1 t1 
on c.name = t1.name                                 ------ Id's join is no need. Because it has one   id.
and c.id = 0                                        ------ 'B' group has been joined
group by c.name, value