sql server如何按照顺序查询最后两条记录,如果用desc方法查询的最后两条记录的顺序就被改变了
比如
string sql = "select top(2)* from table where id='" + id.Text + "' and times='" + times.Text + "'order by 系统时间";
这样查出来的数据就是前面两条记录,而且是按照时间顺序排列的,但是我想按照时间顺序查询最后两条记录,于是写了下面的代码
string sql = "select top(2)* from table where id='" + id.Text + "' and times='" + times.Text + "'order by 系统时间 desc";
但是这个代码写出来后,查询到的记录虽然是最后两条,但是却变成了倒叙
请教各位,如何才能完成顺序查询最后两条记录呢?
再嵌套一层不就完了。
string sql = "select * from (select top(2)* from table where id='" + id.Text + "' and times='" + times.Text + "'order by 系统时间 desc) t order by 系统时间 asc";
子查询就行,先倒叙查询出结果,再正序排序
select * from ( select top(2)* from table where id='" + id.Text + "' and times='" + times.Text + "'order by 系统时间 desc) t order by t.系统时间 asc ;
就像你所说的你已经查出来的两条信息倒序排列,也就是把这两条信息在当成一个新表查询正序排列。select * from (select top(2)* from table where id='" + id.Text + "' and times='" + times.Text + "'order by 系统时间 desc) a order by a.系统时间 asc
先用desc查出top(2)记录,然后再select一次按照asc排序
看下这样行不行:
select * from (select top(2)* from table where id='" + id.Text + "' and times='" + times.Text + "'order by 系统时间 desc) a order by a.系统时间 asc
既然使用C#, 何必还使用原生sql, 用EF不是很方便吗?
// 假设table映射的数据为tables, 按时间顺序取最后2个纪录
var datas = tables.OrderBy(d => d.times).TakeLast(2);
不要写嵌套的那么复杂的SQL了,客户端换下顺序就行了