日期:2014-05-17  浏览次数:20608 次

MSSQL 有没有last函数
就是主表,子表里有多条数,想拿最后一条

------解决方案--------------------
没有这个函数,
 需要通过关系型查询完成


SQL code
select * from 主表,子表 where 主表.id=子表的id
and 子表的时间=(select max(时间字段) from 子表 as t /*这个 as t 不能省略*/where 子表的id=t.子表的id)

------解决方案--------------------
有.

参考:
LAST_VALUE (Transact-SQL)
返回 SQL Server 2012 中有序值集中的最后一个值。

地址:
http://technet.microsoft.com/zh-cn/hh231517(v=sql.100)
------解决方案--------------------
没有这个函数,用游标可以取出来


有排序字段直接

select top 1 * from tb order by 排序字段 desc
------解决方案--------------------
SQL code

declare @T table([id] int,[col] varchar(1))
insert @T
select 1,'a' union all
select 2,'b' union all
select 3,'c'

declare @C table([id] int,[tid] int,[col] int)
insert @C
select 1,1,23 union all
select 2,1,14 union all
select 3,1,18 union all
select 4,2,12 union all
select 5,2,14 union all
select 6,2,15 union all
select 7,3,12 union all
select 8,3,12 union all
select 9,3,10

SELECT  a.* ,b.col
FROM    @T a
        LEFT JOIN @C b ON a.id = b.tid
WHERE   b.id = ( SELECT MAX(id) FROM @C WHERE  tid = b.tid)
/*
id          col  col
----------- ---- -----------
1           a    18
2           b    15
3           c    10
*/

------解决方案--------------------
LAST(column)
返回在指定的域中最后一个记录的值(SQLServer2000 不支持)