如何使用SQL(Max)函数

时间:2014-04-13 08:45:27

标签: sql-server function max

我有2张桌子

Table 1

id     name      adress 
1      John      New York
2      Jane      London`

......等等

Table 2

id    fila      date
1     43        01/01/2010
1     39        10/01/2011
1     55        23/12/2012
2     10        01/01/2008
2     15        02/02/2010`

....等等

我想获得这样的数据

id  fila   name     adress       date
-----------------------------------------
1   55     John    New York    23/12/2012
2   15     Jane    London      02/02/2010

.....等等。

谢谢

4 个答案:

答案 0 :(得分:1)

确定。你真正想要的是“Table1中每一行的最新日期是什么”。所以回答这个问题:

select *
From Table1
inner join (
    select id, max(fila) as maxfila
    from Table2
    group by id
) as maxdates
on Table1.id = maxdates.id
inner join Table2 on Table2.id = maxdates.id AND Table2.fila = maxdates.maxfila

答案 1 :(得分:0)

试试这个:

;with cte as
 (select id, max(fila) maxfila
  from table2
  group by id)
 select t1.id, t1.name, t1.address, t2.fila, t2.date
 from table1 t1 
 left join table2 t2 on t1.id = t2.id
 inner join cte c on t1.id = c.id
 where t2.fila = c.maxfila

答案 2 :(得分:0)

试试这个

Select t1.id, t1.name, t1.address, t2.maxfila
 from table1 t1 
  left outer join 
  (select id, max(fila) maxfila
  from table2
  group by id) t2

答案 3 :(得分:0)

select t1.id, t1.name t1.address, max(t2.fila), 
(select top 1 date from table2 order by fila desc where table2.id = t1.id)
 from table1 t1 inner join 
 table2 t2 on t1.id = t2.id