假设一个Feed表中含有CreateTime(创建时间)和PushCount(被用户推得次数),现在需要先根据CreateTime倒叙排序得出他们的1-n行序号,然后再根据行序号和PushCount的和进行第二次排序,求SQL语句...谢过大侠!
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
*/
使用伪列(rownum)应该就能解决...
SELECT *,ROW_NUMBER() OVER(ORDER BY CreatTime) AS serial FROM a
ORDER BY serial,PushCount
/*创建一个临时表*/
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