Выберите значение самых больших групп / наиболее распространенных значений в таблице мостов в T-SQL - PullRequest
3 голосов
/ 07 ноября 2011

У меня есть таблица, которая представляет «Контракт» между двумя строками в другой таблице. Учитывая данные ниже, как я могу получить наиболее распространенный распределитель для каждого конечного пользователя?

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.

Заранее спасибо! Поиск здесь не сильно помог, потому что трудно описать цель без примеров данных и т. Д.

Ответы [ 2 ]

3 голосов
/ 07 ноября 2011

Не проверено, но я думаю, что это сделает:

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
1 голос
/ 07 ноября 2011
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
...