一个关于如何取出不重复且最新数据的问题!

MUGOER 2016-07-12 12:33:36
数据

序号 期号 标识1
1 1001 3
2 1002 5
3 1003 5
4 1004 6
5 1005 4
6 1006 7
7 1007 9
8 1008 0
9 1009 4


如何从以上数据 以最新的 期号 取出5个不重复的 标识1 字段数据
感谢前辈指教!

...全文
159 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
道玄希言 2016-07-13
  • 打赏
  • 举报
回复


;WITH t1(序号,期号,标识1) AS
(
  select 1,1001,3 union all
  select 2,1002,5 union all
  select 3,1003,5 union all
  select 4,1004,6 union all
  select 5,1005,4 union all
  select 6,1006,7 union all
  select 7,1007,9 union all
  select 8,1008,0 union all
  select 9,1009,4
),
t2 AS
(SELECT row_number() 
   OVER(PARTITION BY 标识1 ORDER by 期号 DESC) AS rn , * 
   from t1
)
SELECT TOP 5 序号,期号,标识1
  from t2 
WHERE rn = 1
ORDER by 期号 DESC
 
/*
9	1009	4
8	1008	0
7	1007	9
6	1006	7
4	1004	6
*/
--小F-- 2016-07-12
  • 打赏
  • 举报
回复
select top 5 * from tb as t where not exists(select 1 from tb where 标识1=t.标识1 and 期号<t.期号) order by 期号
唐诗三百首 2016-07-12
  • 打赏
  • 举报
回复

create table #t
(序号 int, 期号 int, 标识1 int)

insert into #t
  select 1,1001,3 union all
  select 2,1002,5 union all
  select 3,1003,5 union all
  select 4,1004,6 union all
  select 5,1005,4 union all
  select 6,1006,7 union all
  select 7,1007,9 union all
  select 8,1008,0 union all
  select 9,1009,4


with t as(select 标识1,rn=row_number() over(order by 期号 desc) 
               from #t)
select top 5 a.标识1
  from t a
  where not exists(select 1 from t b where b.标识1=a.标识1 and b.rn<a.rn)
  order by a.rn

/*
标识1
-----------
4
0
9
7
6

(5 row(s) affected)
*/
MUGOER 2016-07-12
  • 打赏
  • 举报
回复
select top 5 * from tb as t where not exists(select 1 from tb where 标识1=t.标识1 and 期号<t.期号) order by 期号
select top 5 * from tb as t where not exists(select 1 from tb where 标识1=t.标识1 and 期号> t.期号) order by 期号
执行代码后,获取出的不能达到预期的效果,以下图片选中的是通过上述语句获取到的,实际要的是被我用红色圈起来的因为最新的五条数据 标识1 没有重复直接取出!
Ginnnnnnnn 2016-07-12
  • 打赏
  • 举报
回复
select top 5 * from tb as t where not exists(select 1 from tb where 标识1=t.标识1 and 期号> t.期号) order by 期号
MUGOER 2016-07-12
  • 打赏
  • 举报
回复
引用 3 楼 fredrickhu 的回复:
那就你上面的数据 需要得到的结果应该是怎样的?
1 1001 3 2 1002 5 3 1003 5 4 1004 6 5 1005 4 6 1006 7 7 1007 9 8 1008 0 9 1009 4 以期号最大优先取出 或 ID 最大优先取出 不重复的 标识1 数据,谢谢
--小F-- 2016-07-12
  • 打赏
  • 举报
回复
那就你上面的数据 需要得到的结果应该是怎样的?
MUGOER 2016-07-12
  • 打赏
  • 举报
回复
引用 1 楼 fredrickhu 的回复:
select top 5 * from tb as t where not exists(select 1 from tb where 标识1=t.标识1 and 期号<t.期号) order by 期号
感谢版主的回复,根据您写的语句,无法从可以取得不重复的5条数据,但是无法 取得最新 期号 的五条数据。

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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