查询与联接的总和排名最高的值

时间:2016-12-09 14:55:25

标签: mysql sql

我写了一个查询,输出所有员工的销售数字,他们的名字以及他们在哪个商店工作。但我正在努力寻找每个商店的顶级销售人员。您能解释一下我如何只展示每个商店的顶级销售人员。我以为我可以用

SELECT empname, shopname, SUM( rentalrate ) AS Sales
FROM frs_FilmRental
NATURAL JOIN frs_Employee
NATURAL JOIN frs_Shop
GROUP BY empnin, shopname

这是我的截图 到目前为止Results

2 个答案:

答案 0 :(得分:0)

这是一个非常丑陋的方式:

SELECT t1.empname,
       t1.shopname,
       t2.maxsales
FROM
(
    SELECT empname, shopname, SUM(rentalrate) AS sales
    FROM frs_FilmRental
    NATURAL JOIN frs_Employee
    NATURAL JOIN frs_Shop
    GROUP BY empname, shopname
) t1
INNER JOIN
(
    SELECT t.shopname, MAX(t.Sales) AS maxsales
    FROM
    (
        SELECT shopname, SUM(rentalrate) AS Sales
        FROM frs_FilmRental
        NATURAL JOIN frs_Employee
        NATURAL JOIN frs_Shop
        GROUP BY empname, shopname
    ) t
    GROUP BY t.shopname
) t2
    ON t1.shopname = t2.shopname AND
       t1.sales    = t2.maxsales

您将子查询t1视为原始查询。 t2子查询将此结果集限制为仅具有最高销售额的商店,仅表示与销售额最高的员工相对应的记录。如果出现平局,将为该商店退回两份记录。

查询有点冗长,但部分原因是MySQL不支持行号或公用表表达式。

答案 1 :(得分:0)

   SELECT *
    FROM
    (
      SELECT DISTINCT empname, shopname,
      SUM( rentalrate ) OVER (PARTITION BY shopname,empname ) AS Sales,
      ROW_NUMBER OVER (PARTITION BY shopname,empname ) AS RN
      FROM frs_FilmRental
      NATURAL JOIN frs_Employee
      NATURAL JOIN frs_Shop
      GROUP BY empnin, shopname 
                                 ) X
    WHERE X.RN=1