首页 新闻 会员 周边

求SQL语句

0
悬赏园豆:100 [已解决问题] 解决于 2011-03-30 10:46

假设一个Feed表中含有CreateTime(创建时间)和PushCount(被用户推得次数),现在需要先根据CreateTime倒叙排序得出他们的1-n行序号,然后再根据行序号和PushCount的和进行第二次排序,求SQL语句...谢过大侠!

问题补充: 数据量可能比较多,这种排序与单纯的按时间排序会不会耗很多的性能
89的主页 89 | 初学一级 | 园豆:0
提问于:2011-03-29 23:58
< >
分享
最佳答案
0

SQL2005以上:

 

IF NOT OBJECT_ID('[Feed]') IS NULL
DROP TABLE [Feed]
GO
CREATE TABLE [Feed]
(
[ID] int identity(1,1) primary key not null,
[TAG] nvarchar(255) null,
[CreateTime] datetime not null default(getdate()),
[PushCount] bigint not null default(0)
)
go


insert into [Feed]
SELECT 'AAA','2011-01-10',23 union all
SELECT 'EEE','2011-02-23',345 union all
SELECT 'CCC',getdate(),56 union all
SELECT 'BBB',Dateadd(dd,2,getdate()),99 union all
SELECT 'DDD',getdate(),235 union all
SELECT 'KKK',Dateadd(dd,-4,getdate()),2356 union all
SELECT 'SSS',getdate(),400 union all
SELECT 'XXX',Dateadd(dd,-234,getdate()),346
go


--select * from [Feed]
/*

ID TAG CreateTime PushCount
1 AAA 2011-01-10 00:00:00.000 23
2 EEE 2011-02-23 00:00:00.000 345
3 CCC 2011-03-30 08:28:20.467 56
4 BBB 2011-04-01 08:28:20.467 99
5 DDD 2011-03-30 08:28:20.467 235
6 KKK 2011-03-26 08:28:20.467 2356
7 SSS 2011-03-30 08:28:20.467 400
8 XXX 2010-08-08 08:28:20.467 346
*/


Select S.ID, S.RowID,S.TAG,S.CreateTime,S.PushCount
,(S.RowID
+S.PushCount)as NewTotalID
From [Feed] T
inner Join
(
Select Row_Number() over(Order by CreateTime Desc) As RowID,
ID, TAG,CreateTime,PushCount
From [Feed]
) S
On T.TAG = S.TAG
Where 1=1
order by NewTotalID desc

/*
ID RowID TAG CreateTime PushCount NewTotalID
6 5 KKK 2011-03-26 08:28:20.467 2356 2361
7 3 SSS 2011-03-30 08:28:20.467 400 403
8 8 XXX 2010-08-08 08:28:20.467 346 354
2 6 EEE 2011-02-23 00:00:00.000 345 351
5 2 DDD 2011-03-30 08:28:20.467 235 237
4 1 BBB 2011-04-01 08:28:20.467 99 100
3 4 CCC 2011-03-30 08:28:20.467 56 60
1 7 AAA 2011-01-10 00:00:00.000 23 30
*/
收获园豆:100
邀月 | 高人七级 |园豆:25475 | 2011-03-30 08:38
谢谢邀月兄! 这种做法跟纯粹的按时间排序性能差异大不,在大表中适合不?
89 | 园豆:0 (初学一级) | 2011-03-30 10:47
@
89:调用的是 SQL Serer的内部函数,百万以下的数据,取TOP数千条应该没有问题。
邀月 | 园豆:25475 (高人七级) | 2011-03-30 13:12
其他回答(3)
0

使用伪列(rownum)应该就能解决...

oraclexp | 园豆:100 (初学一级) | 2011-03-30 00:29
0

SELECT   *,ROW_NUMBER() OVER(ORDER BY CreatTime) AS serial FROM a
ORDER BY serial,PushCount

peter cheng | 园豆:431 (菜鸟二级) | 2011-03-30 08:37
这就是纯粹按时间排序了
支持(0) 反对(0) 89 | 园豆:0 (初学一级) | 2011-03-30 10:48
0

/*创建一个临时表*/
create table #temp
(
id
int identity(1,1),
createtime
datetime,
pushcount
int,
f
varchar(50)--其他需要查询的字段
)
select createtime,pushcount,f
into
#
temp
from feed order by createtime/*先倒序排*/

/*那么现在 #temp 中的 数据 就是 按照 createtime 倒序的,id 就是序号.*/
--再排序
select * from #temp order by pushcount desc,id asc

$克 | 园豆:217 (菜鸟二级) | 2011-03-30 08:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册