如何从select查询中将最后一条记录保存到变量中?

时间:2016-06-18 15:24:01

标签: sql-server

我是sql server的初学者,编写此查询以从表中选择任何数据:

select   phoneNumber,sum(Duration) sumPrice
    from CDR
    where Date_>=@var1 and Time>@var2
    group by phoneNumber


查询返回大约800万条记录,我想将最后一条记录时间字段保存到其他变量中,例如:

select   phoneNumber,sum(Duration) sumPrice
from CDR
where Date_>=@var1 and Time>@var2
group by phoneNumber
@Time=last up query time column


我该怎么写呢?感谢每一个人。

2 个答案:

答案 0 :(得分:1)

Declare @Date Date,@Time Time  -- Assuming a Time field 

Select Top 1 @Date=Date_,@Time=Time
  From CDR
  Where Date_>=@var1 and Time>@var2
  Order By Date_ Desc, Time Desc

Select @Date,@Time

答案 1 :(得分:0)

试试这个:

Set @Time = (Select Top 1 Time
  From CDR
  Where Date_>=@var1 and Time>@var2
  Order By Date_ Desc, Time Desc)

如果您需要选择更多列,则需要使用:

Select Top 1 @Time=Time, Col1, Col2
From CDR
Where Date_>=@var1 and Time>@var2
Order By Date_ Desc, Time Desc