SQL Server每个分类取最新的几条的SQL实现代码
发布时间:2020-12-12 07:41:08 所属栏目:MsSql教程 来源:网络整理
导读:感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧! CREATE TABLE table1( [ID] [bigint] IDENTITY(1,1) NOT NULL,[Name] [nvarchar](128) NOT NULL,[class] int not null,[date] datetime not null)class 表示分类编号。 分类数不固定,
感兴趣的小伙伴,下面一起跟随编程之家 52php.cn的小编两巴掌来看看吧! CREATE TABLE table1( [ID] [bigint] IDENTITY(1,1) NOT NULL,[Name] [nvarchar](128) NOT NULL,[class] int not null,[date] datetime not null)class 表示分类编号。 分类数不固定, 至少有上千种分类date 表示该条记录被更新的时间 我们现在想获得每个分类最新被更新的5条记录。 解决方案 select id,name,class,date from(select id,date,row_number() over(partition by class order by date desc)as rowindex from table1) awhere rowindex <= 5 create table #temp ( company varchar(50), product varchar(50), inputDate datetime ) insert into #temp(company,product,inputDate) values('杭州大明有限公司','汽车1','2010-8-1') insert into #temp(company,'汽车2','汽车3','汽车4','汽车5','2010-7-1') insert into #temp(company,inputDate) values('北京小科有限公司',inputDate) values('上海有得有限公司',inputDate) values('天津旺旺有限公司','2010-8-1') select * from #temp create proc getdata @num int as begin select top 4 * from ( select ( select count(*) from #temp where company=a.company and product<=a.product) as 序号,a.company,a.product,a.inputDate from #temp a ) b where 序号>=@num order by 序号,inputDate desc end go getdata 2 /* 结果 1 杭州大明有限公司 汽车1 2010-08-01 00:00:00.000 1 北京小科有限公司 汽车1 2010-08-01 00:00:00.000 1 上海有得有限公司 汽车1 2010-08-01 00:00:00.000 1 天津旺旺有限公司 汽车4 2010-08-01 00:00:00.000 2 天津旺旺有限公司 汽车5 2010-08-01 00:00:00.000 2 上海有得有限公司 汽车2 2010-08-01 00:00:00.000 2 北京小科有限公司 汽车2 2010-08-01 00:00:00.000 2 杭州大明有限公司 汽车2 2010-08-01 00:00:00.000 3 杭州大明有限公司 汽车3 2010-08-01 00:00:00.000 3 北京小科有限公司 汽车3 2010-08-01 00:00:00.000 3 上海有得有限公司 汽车3 2010-08-01 00:00:00.000 4 北京小科有限公司 汽车4 2010-08-01 00:00:00.000 4 北京小科有限公司 汽车4 2010-08-01 00:00:00.000 4 上海有得有限公司 汽车4 2010-08-01 00:00:00.000 4 杭州大明有限公司 汽车4 2010-08-01 00:00:00.000 5 杭州大明有限公司 汽车5 2010-07-01 00:00:00.000 */ --sql2005 create proc getdata2005 @num int as begin select top 4 * from ( select row_number() over (partition by company order by product ) as 序号,inputDate desc end getdata2005 4 select * from #temp select ( select count(*) from #temp where company+ product<=a.company+a.product) as 序号,a.inputDate ,a.company+a.product as 唯一标志一行 from #temp a order by company,product 代码如下:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- SQLServer存储过程的返回值 查询分析器/程序
- 在PostgreSQL的基础上创建一个MongoDB的副本的教程
- 最近浏览记录
- sql-server – 为什么在我的测试用例中,顺序GUID键的执行速
- 如何将sql执行的错误消息记录到本地文件中实现过程
- SQLServer RESOURCE_SEMAPHORE 等待状态
- sql-server – VMware中的SQL Server
- SQL2005企业管理器远程连接非默认端口SQL2005数据库的解决办
- sql-server-2005 – 无法在Vista x64上从Visual Studio 200
- sql-server – 如何判断Snapshot Isolation是否已打开?