2009-08-28 34 views
0

我在SQL Server 2005中的表變量:選擇從表變量的最高得分結果在SQL

DECLARE @results TABLE (id int IDENTITY(1,1), 
         customerId int, 
         salesId int, 
         score int, 
         lastServiceDate datetime, 
         PRIMARY KEY(id)); 

我需要一個有效的方式來擦桌子或訪問表的結果,所以它每個salesId只返回1個結果。如果每個salesId的結果不止一個,它應顯示最高分數的行,或者在平行的情況下顯示Customer表中最近一次的lastServiceDate。

現在,我的測試數據是這樣的:

id customerId salesId score lastServiceDate 
1 950   418  3  2009-08-09 00:00:00.000 
2 951   418  3  2009-08-19 00:00:00.000 
3 952   418  1  2009-08-22 00:00:00.000 
4 953   419  2  2009-08-15 00:00:00.000 

我想要的東西,將返回,在這種情況下,只是兩行 - ID 2(最高分/ lastServiceDate爲salesId 418)和id 4(僅針對salesId 419的結果)。最後,我需要獲取此表中的數據,並將其插入到JobResult表中,並從這些限制中選擇@results中的customerId和salesId。

(這完成在https://stackoverflow.com/questions/1343647問了一個問題。)

+1

爲什麼值得這個是「表變量」,由@標識標識,而#結果是一個臨時表。 @在內存中,#在磁盤上。 –

+0

因此,無論客戶是誰,都希望每個salesId有1行?如果salesId 3在同一天爲兩個客戶提供服務並且每個客戶都獲得完全相同的分數,該怎麼辦?什麼應該插入到你的JobResult表中? –

回答

1

這將返回你想要的數據:

SELECT id, salesId, score, lastServiceDate 
from (select id, salesId, score, lastServiceDate 
     ,row_number() over(partition by SalesId order by score desc, lastServiceDate desc) ranking 
     from @results) xx 
where xx.ranking = 1 

,這將刪除不需要的行該表只留下你想要的:

DELETE @results 
where id in (select id 
       from (select id, salesId, score, lastServiceDate 
         ,row_number() over(partition by SalesId order by score desc, lastServiceDate desc) ranking 
         from @results) xx 
       where xx.ranking <> 1) 

select * from @results 

我使用您發佈的數據對此進行了測試,但請務必使用更大/更復雜的數據集進行測試。

0

試試這個:

WITH highscore AS (
     SELECT r.salesid, 
       MAX(r.score) 'maxscore', 
       MAX(t.lastservicedate) 'maxservicedate' 
     FROM @results r 
    GROUP BY r.salesid) 
    SELECT t.customerid, 
     t.salesid, 
     t.lastservicedate 
    FROM @results t 
    JOIN highscore hs ON hs.salesid = t.salesid 
        AND hs.maxscore = t.score 
        AND hs.maxservicedate = t.lastservice 
GROUP BY t.customerid, 
     t.salesid 
+0

這對於削減最高分數結果當然似乎是正確的,但它對於lastservicedate似乎不起作用 - 它不會以這種方式分割組。 – Brisbe42

+0

@Brisbe:立即嘗試,從 –

+0

組中刪除lastservicedate更新:更正了CTE和後續的連接子句。 –