回答你的問題的第一部分取決於該版本的SQL服務器的你使用 - SQL 2005+提供了ranking functions,這使得這種查詢比SQL 2000和之前更簡單一些。如果您將指出您正在使用哪個平臺,我會更詳細地更新它。
我懷疑處理第2部分最明顯的方法是顯示最新的完整刮擦練習的統計數據,否則你不顯示時間一致的排名(儘管如果你的數據收集練習需要24小時,一定的緯度已經)。
爲了簡化這一點,您可以創建一個表來保存關於每個刮擦操作的元數據,爲每個刮擦操作提供一個id,開始日期和完成日期(至少),並顯示與最新完整刮擦相關的記錄。爲了使這更容易,您可以從數據收集表中刪除「刮日期」,並將其替換爲將每個數據行鏈接到刮表中的行的外鍵。
編輯
下面的代碼演示瞭如何通過他們最新的得分排名的用戶,不管他們是否有時間一致:
create table #scrape
(userName varchar(20)
,wins int
,losses int
,scrapeDate datetime
)
INSERT #scrape
select 'Alice',100,200,'20090101'
union select 'Alice',120,210,'20090201'
union select 'Bob' ,200,200,'20090101'
union select 'Clara',300,100,'20090101'
union select 'Clara',300,210,'20090201'
union select 'Dave' ,100,10 ,'20090101'
;with latestScrapeCTE
AS
(
SELECT *
,ROW_NUMBER() OVER (PARTITION BY userName
ORDER BY scrapeDate desc
) AS rn
,wins + losses AS totalPlayed
,wins - losses as winDiff
from #scrape
)
SELECT userName
,wins
,losses
,scrapeDate
,winDiff
,totalPlayed
,RANK() OVER (ORDER BY winDiff desc
,totalPlayed desc
) as rankPos
FROM latestScrapeCTE
WHERE rn = 1
ORDER BY rankPos
EDIT 2
一個例證使用元數據表來選擇最新的完整刮:
create table #scrape_run
(runID int identity
,startDate datetime
,completedDate datetime
)
create table #scrape
(userName varchar(20)
,wins int
,losses int
,scrapeRunID int
)
INSERT #scrape_run
select '20090101', '20090102'
union select '20090201', null --null completion date indicates that the scrape is not complete
INSERT #scrape
select 'Alice',100,200,1
union select 'Alice',120,210,2
union select 'Bob' ,200,200,1
union select 'Clara',300,100,1
union select 'Clara',300,210,2
union select 'Dave' ,100,10 ,1
;with latestScrapeCTE
AS
(
SELECT TOP 1 runID
,startDate
FROM #scrape_run
WHERE completedDate IS NOT NULL
)
SELECT userName
,wins
,losses
,startDate AS scrapeDate
,wins - losses AS winDiff
,wins + losses AS totalPlayed
,RANK() OVER (ORDER BY (wins - losses) desc
,(wins + losses) desc
) as rankPos
FROM #scrape
JOIN latestScrapeCTE
ON runID = scrapeRunID
ORDER BY rankPos
哪個版本的SQL Server? – 2009-09-09 06:49:43
將使用MSSQL – Fatal510 2009-09-09 06:52:12
但是哪個版本,SQL 7,SQL 2000,SQL 2005,SQL 2008,SQL 2008 R2? – mrdenny 2009-09-09 07:34:58