求一条排序筛选SQL语句的写法?

flyseagod 2009-05-28 09:25:17
将表中的数据按时间排序,然后取出前后两条其中指定字段记录不同的SQl语句。比如说按排序后一个字段的记录是a a a b c c ,那么我要得到的是a b c ,请各位大侠帮忙。
...全文
102 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
lihan6415151528 2009-05-29
  • 打赏
  • 举报
回复

select * from tb t where not exists(select 1 from tb where col=t.col and 时间<t.时间)
ch315537 2009-05-29
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ChinaJiaBing 的回复:]
SQL codedeclare@tbtable(namenvarchar(10),时间datetime)insertinto@tbselect'a','2009-5-21'unionallselect'a','2009-5-22'unionallselect'a','2009-5-23'unionallselect'b','2009-5-24'unionallselect'c','2009-5-25'unionallselect'c','2009-5-26'--select *,ID=ROW_NUMBER()over( partition by name order by 时间 desc) from @tb order by 时间 descselecttop2name,时间from(select*,ID=ROW_NUMBER()over( partitionbynam…
[/Quote]
学习学习
ks_reny 2009-05-28
  • 打赏
  • 举报
回复
4楼的效率高。
flyseagod 2009-05-28
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 flyseagod 的回复:]
引用 1 楼 happyflystone 的回复:
select *
from ta a
where exists(select 1 from ta where id = a.id - 1 and col != a.col)
and
exists(select 1 from ta where id = a.id + 1 and col != a.col)

这个好像不能得到想要结果
[/Quote]
把and改成or后可以,最好是能按时间排序
Zoezs 2009-05-28
  • 打赏
  • 举报
回复

select * from tb a where
not exists(select 1 from tb where col=a.col and 时间<a.时间)
百年树人 2009-05-28
  • 打赏
  • 举报
回复
select 
*
from
tb t
where
not exists(select 1 from tb where col=t.col and 时间<t.时间)
ChinaJiaBing 2009-05-28
  • 打赏
  • 举报
回复


declare @tb table (name nvarchar(10),时间 datetime)
insert into @tb select 'a','2009-5-21'
union all select 'a','2009-5-22'
union all select 'a','2009-5-23'
union all select 'b','2009-5-24'
union all select 'c','2009-5-25'
union all select 'c','2009-5-26'
--select *,ID=ROW_NUMBER()over( partition by name order by 时间 desc) from @tb order by 时间 desc
select top 2 name,时间 from(
select *,ID=ROW_NUMBER()over( partition by name order by 时间) from @tb) a where ID=1
union
select top 2 name,时间 from (
select top 100 *,ID=ROW_NUMBER()over( partition by name order by 时间 desc) from @tb order by 时间 desc) b where ID=1


name 时间
---------- -----------------------
a 2009-05-21 00:00:00.000
b 2009-05-24 00:00:00.000
c 2009-05-26 00:00:00.000

(3 行受影响)

flyseagod 2009-05-28
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 happyflystone 的回复:]
select *
from ta a
where exists(select 1 from ta where id = a.id - 1 and col != a.col)
and
exists(select 1 from ta where id = a.id + 1 and col != a.col)
[/Quote]
这个好像不能得到想要结果
-狙击手- 2009-05-28
  • 打赏
  • 举报
回复
select *
from ta a
where exists(select 1 from ta where id = a.id - 1 and col != a.col)
and
exists(select 1 from ta where id = a.id + 1 and col != a.col)

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧