日期:2014-05-18 浏览次数:20585 次
select
*
from
tbl_log a
where
tl_time=(select max(tl_time) from tbl_log where tl_car=a.tl_car and tl_car in(441,442))
------解决方案--------------------
your query looks ok. To write a procedure without setting a fixed list of ids, you can do something like this:
create proc getRecentRec(@idList nvarchar(1000))
AS
Begin
if charindex(',', @idList)>0 -- a list
Begin
declare @sql nvarchar(1000)
set @sql =
'select * from tbl_log t
where tl_car in (' + @idList + ')
AND tl_time = (select max(tl_time) from tbl_log where tl_car = t.tl_car)'
exec(@sql)
End
else
Begin
select * from tbl_log t
where tl_car = @idList And tl_time = (select max(tl_time) from tbl_log where tl_car = t.tl_car)
End
End
------解决方案--------------------
--静态——固定两个:tl_car in (441,442)
select * from tbl_log a where tl_car in (441,442) and tl_time=(select max(tl_time) from tbl_log where tl_car=a.tl_car)
--动态SQL查多个tl_car:
declare @tl_cars varchar(1000)
set @tl_cars='441,443,446,447'
exec ('select * from tbl_log a where tl_car in ('+@tl_cars+') and tl_time=(select max(tl_time) from tbl_log where tl_car=a.tl_car)')