从表中检索具有最大计数的项目列表

时间:2015-09-04 05:39:20

标签: sql sql-server stored-procedures

我有2个表DistributorReseller,并且有像

这样的列

分销商

  id, name

经销商

 Id name ChildDistriid 

我想选择拥有最大转销商的经销商的详细信息。

到目前为止,这是我的代码:

alter procedure sp
as
begin
    with CTE_RN as
    (
        select 
            d.name as Distributor,
            r.name as Reseller,
            count(r.childdistributorid) over (partition by r.childdistributorid) as Rcount 
        from 
            distributor d
        join 
            reseller r on r.childdistributorid = d.id 
        group by 
            d.name, r.name, r.childdistributorid 
    )
    select * 
    from CTE_RN  
    group by Distributor, Reseller 
    having Rcount = max(Rcount)
end

exec sp

2 个答案:

答案 0 :(得分:2)

如果没有错,你需要这个

SELECT TOP 1 WITH ties *
FROM   (SELECT d.name                                 AS Distributor,
               r.name                                 AS Reseller,
               Count(r.childdistributorid)OVER (partition BY r.childdistributorid) AS Rcount
        FROM   distributor d
               JOIN reseller r
                 ON r.childdistributorid = d.id) a
ORDER  BY Rcount DESC 

答案 1 :(得分:0)

改变程序sp 如

begin

with CTE_RN as
(
select d.name as Distributor,r.name as Reseller,count(r.childdistributorid) over (partition by r.childdistributorid) as Rcount from distributor d
join reseller r on r.childdistributorid=d.id group by 
d.name,r.name,r.childdistributorid 
)
select * from CTE_RN  where Rcount=(select max(Rcount) from CTE_RN )
end
exec sp