2011-11-07 90 views
3

我有一張表,它表示另一個表中兩行之間的「合同」。鑑於以下數據,我如何才能爲每個EndUser獲取最常見的Distributer?選擇T-SQL中橋表中最大組/最常見值的值

Contracts 

EndUserId | DistributerId | StartDate | EndDate 
----------------------------------------- 
1   | 8    | ...  | ... 
1   | 9    | ...  | ... 
1   | 9    | ...  | ... 
2   | 8    | ...  | ... 
2   | 8    | ...  | ... 
2   | 9    | ...  | ... 
3   | 8    | ...  | ... 
3   | 9    | ...  | ... 

查詢後,我必須返回如下:

EndUserId | DistributerId 
------------------------- 
1   | 9 
2   | 8 
3   | 8 or 9, it is of no consequence. 

提前感謝!搜索沒來了太大的幫助,因爲它是很難描述的目的,而不樣本數據等

回答

3

未經檢驗的,但我認爲這將做到這一點:

WITH ContractCounts AS 
(--First Get the counts for each distributer 
    SELECT EndUserID, DistributerID, Count(*) As ContractCount 
    FROM Contracts 
    GROUP BY EndUserID, DistributerID 
), 
ContractMax AS 
( -- Then find out how many contracts the largest distributed for each user had 
    SELECT EndUserID, Max(ContractCount) As MaxContractCount 
    FROM ContractCounts 
    GROUP BY EndUserID 
) 
-- and finally select only the distributor for each user who's count matches the prior query 
SELECT c.EndUserID, MAX(c.DistributerID) AS DistributerID 
FROM ContractCounts c 
INNER JOIN ContractMax m on m.EndUserID=c.EndUserID AND c.ContractCount = m.MaxContractCount 
GROUP BY c.EndUserID 
+0

嘿夥計,這是完美的,除了在我的例子中,對於EndUserId 3,它將返回兩行,一個是8,另一個是9.我提交了一個編輯,增加了一個GROUP BY和MAX,它簡單地獲取了其中一個值。謝謝! – andrej351

+2

@ andrej351,你的建議編輯被用戶拒絕(我懷疑沒有分析問題和答案,也沒有說明你是OP)。 ...因爲這個變化是讓你的答案爲你工作的 - 提問者 - 我爲你編輯它。 Joel Coehoorn如果不喜歡這個變化,他可以恢復。 –

1
select * 
from 
(
    select *, row_number() over(partition by EndUser order by UserDistCount desc) as rownum 
    from 
    (
     select EndUserId, DistributorId, count(*) as UserDistCount 
     from Contracts 
     group by EndUserId, DistributorId 
    ) a 
) b 
where rownum = 1 
+0

我更喜歡這個解決方案,因爲:1)固有地解決了「在綁定情況下任意返回1值」的問題;和2)通過將rownum = 1更改爲rownum <= n,其他應用程序可以將其推廣到「返回頂部'n'條目」 –