Sql server 如何使用SQL(Max)函数
我有两张桌子Sql server 如何使用SQL(Max)函数,sql-server,function,max,Sql Server,Function,Max,我有两张桌子 表1: id name adress 1 John New York 2 Jane London` 。。。等等 表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/2
表1
:
id name adress
1 John New York
2 Jane London`
。。。等等
表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
。。。。。等等
谢谢试试这个:
;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
嗯。您真正想要的是“表1中我的每一行在表2中的最新日期是什么”。因此,要回答这个问题:
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
试试这个
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
您还需要一个join来获取
fila
值。我需要从表2中的每个id中获取最大值(fila),并将结果与表1中的数据相结合:名称、地址):@atty尝试一下。您是在寻找max(fila)
还是max(日期)
?这两种方法都适用于给定的示例,但我想确定一下。我需要表2中每个id中的max(fila)并与表1中的数据结合起来,谢谢,谢谢澄清。您可以尝试我的答案,并让我知道它是否适用于您。不适用。我使用表2中每个id的nedd max(fila)与表1中的数据相结合您是否知道如何使用此解决方案创建sql视图?您可能想看看以下内容:
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