我有3个表(SQL Server 2008 R2):
ID Date
123 20-08-2011
123 20-08-2011
234 30-09-2012
ID Centre ChangeDate
123 987 16-08-11
123 568 28-05-10
234 456 14-09-12
Centre Centre_Name
987 test1
568 test2
456 test3
我想进行一个查询,该查询将所有列连接在一起,并且仅选择具有最大ChangeDate的Center。因此,应返回下表:
ID Date Centre ChangeDate Centre_Name
123 20-08-11 987 16-08-11 test1
123 20-08-11 987 16-08-11 test1
234 30-09-12 456 14-09-12 test3
谢谢。
答案 0 :(得分:0)
应该有多种方法来实现您的结果。一种方法是使用通过[Id]列(如果希望具有最高[ChangeDate]的Id / Centre组合的ID或[Centre])划分的row_number()。这将产生独特的结果,并且不符合您的答案中所述的期望结果(我的问题是:为什么要重复答案?)。另一种方法是使用子查询从每个ID中的表2中检索最大更改,然后将结果第二次连接到表2中。
declare @table1 table ([Id] INT, [Date] date)
declare @table2 table ([Id] INT, [Centre] int, [ChangeDate] date)
declare @table3 table ([Centre] int, [Centre_Name] varchar(25))
insert into @table1 values (123,'2011-08-20'),(123,'2011-08-20'),(234,'2012-09-30')
insert into @table2 values (123,987,'2011-08-16'),(123,568,'2010-05-28'),(234,456,'2012-09-14')
insert into @table3 values (987,'test1'),(568,'test2'),(456,'test3')
方法1:使用row_number()
select *
from (
select t1.[Id],t1.[Date],t2.[Centre],t2.[ChangeDate],t3.[Centre_Name]
, rn=row_number() over (partition by t2.[Id]/*, t2.[Centre]*/ order by t2.[ChangeDate] desc)
from @table1 t1
join @table2 t2 on t2.Id = t1.Id
join @table3 t3 on t3.Centre=t2.Centre
) x where x.rn=1
方法2:使用子查询检索每个[Id]的最大[ChangeDate]
select t1.[Id],t1.[Date],t2.[Centre],t2.[ChangeDate],t3.[Centre_Name]
from @table1 t1
join (select Id, maxChangeDate=max(ChangeDate) from @table2 group by Id ) t2_maxChangeDate on t1.[Id]=t2_maxChangeDate.[Id]
join @table2 t2 on t2.[Id]=t2_maxChangeDate.[Id] and t2.[ChangeDate]=t2_maxChangeDate.[maxChangeDate]
join @table3 t3 on t3.[Centre] = t2.[Centre]
答案 1 :(得分:0)
我会使用apply
:
select t1.*, tt.*
from table1 t1 cross apply
( select top (1) t2.Centre, t2.ChangeDate, t3.Centre_Name
from table2 t2 inner join
table3 t3
on t3.Centre = t2.Centre
where t2.id = t1.id
order by t2.ChangeDate desc
) tt;