从经销商表中选择最畅销的销售额

时间:2015-01-28 16:45:19

标签: sql-server tsql

首先我有代理商,每个代理商都有经销商。我有一个包含所有代理的代理表。我有一份合同表,其中列出了所有销售。我有一个经销商桌子,将所有经销商都联系到代理商。

SELECT a.agent_name, COUNT(distinct c.dealer_number) as '# of Selling Dealers'
FROM agents a
inner join contracts c on c.agent_number = a.agent_number
inner join dealers d on d.agent_number = a.agent_number 
group by agent_name

例如,如果我现在运行此查询将返回

Agent Name     # of selling Dealers
Agent #1            6

我现在需要弄清楚的是谁是最畅销的产品以及销售量。此信息将在合同表中。

因此,在示例Agent #1中有6位经销商进行了销售。让假装Dealer #5该列表的销售额最高。

所以它应该返回如下:

Agent Name     # of selling Dealers      Top Dealer      Volume
Agent #1            6                     Dealer #5        24

我想退回畅销书的经销商名称和他们获得的销售数量(也在合同表中)。

其他信息

合约表中的每一行都算作销售。它将包含dealer_namedealer_numberagent_nameagent_number

代理程序表有agent_name,agent_number 经销商表有dealer_name,dealer_number,agent_number 合约表有agent_number,dealer_number

2 个答案:

答案 0 :(得分:0)

SELECT
    m.agent_name, 
    max_dealer_contract_sales,
    dealer_name
FROM 
    (SELECT
        agent_name, 
        MAX(dealer_contract_sales) AS max_dealer_contract_sales
    FROM 
        (SELECT 
            agent_name, 
            dealer_name,
            COUNT(dealer_name) AS dealer_contract_sales
        FROM 
            contracts 
        GROUP BY 
            agent_name, 
            dealer_name) c
    GROUP BY
        agent_name) m INNER JOIN
    (SELECT 
        agent_name, 
        dealer_name,
        COUNT(dealer_name) AS dealer_contract_sales
    FROM 
        contracts 
    GROUP BY 
        agent_name, 
        dealer_name) c ON
        m.agent_name = c.agent_name AND
        max_dealer_contract_sales = dealer_contract_sales

答案 1 :(得分:0)

;with AgentPerformance as
(
  SELECT agent_number, count(distinct c.dealer_number) as SellingDealers
  FROM contracts
  GROUP BY agent_number, 
), DealerPerformance as
(
  SELECT agent_number, dealer_number, count(*) DealerSalesCnt
  FROM contracts
  GROUP BY agent_number, dealer_number,
), TopDealersTmp as
(
  SELECT agent_number, dealer_number, DealerSalesCnt,
    row_number() over (partition by agent_number order by DealerSalesCnt desc) rn
  FROM DealerPerformance
), TopDealers as
(
  SELECT agent_number, dealer_number, DealerSalesCnt
  FROM TopDealersTmp
  WHERE rn = 1
)
SELECT a.agent_name, ap.SellingDealers, d.dealer_name, td.DealerSalesCnt
FROM AgentPerformance ap
  join agents a
    on ap.agent_number = a.agent_number
  join TopDealers td
    on ap.agent_number = td.agent_number
  join dealers d
    on d.dealer_number = td.dealer_number

在AgentPerformance中,我计算销售经销商的数量。

在经销商绩效中,我计算每个经销商的销售量(稍后选择最佳销售量)。

在TopDealersTmp中,我根据每个代理商的最佳表现者的表现重新为经销商编号。

在TopDealers中,我只选择表现最佳的人。

在最终选择中,我按数字拉名称并输出。