我正在尝试为特定商店的特定员工获取MAX计数。我可以很容易地得到每个员工的数量以及他们在哪个商店工作,但我只想在每个商店中排名前1位。
SELECT Emp_ID || ': ' || First_Name || ' ' || Last_Name AS "Emp. Name",
Store_Num || ': ' || Store_Name AS "Store",
COUNT(Emp_ID) AS "Num Rentals"
FROM Employee JOIN rental USING (Emp_ID)
JOIN store USING (Store_Num)
GROUP BY Emp_ID, First_Name, Last_Name, Store_Num, Store_Name;
Emp. Name Store Num Rentals
-------------------- -------------------- -----------
104: Victoria Lee 20: SQ Hill's DVD 4
102: Steve Baker 10: Oakland's DVD 3
103: Lily Evans 10: Oakland's DVD 3
105: Gloria Tremblay 20: SQ Hill's DVD 4
101: Jim Smith 10: Oakland's DVD 5
106: Emma Wesley 30: DVD Hub 3
6 rows selected.
这可以获得每个员工处理的租金数量以及他们在哪个商店工作。我只想在每家商店找到最优秀的员工。结果表应该是......
Emp. Name Store Num Rentals
-------------------- -------------------- -----------
104: Victoria Lee 20: SQ Hill's DVD 4
105: Gloria Tremblay 20: SQ Hill's DVD 4
101: Jim Smith 10: Oakland's DVD 5
106: Emma Wesley 30: DVD Hub 3
提前感谢您的所有帮助!
答案 0 :(得分:4)
您可以使用分析函数RANK:
select "Emp. Name", "Store", "Num Rentals" FROM
(SELECT Emp_ID || ': ' || First_Name || ' ' || Last_Name AS "Emp. Name",
Store_Num || ': ' || Store_Name AS "Store",
COUNT(Emp_ID) AS "Num Rentals",
rank() over(partition by Store_Num, Store_Name order by COUNT(Emp_ID) desc) rw
FROM Employee JOIN rental USING (Emp_ID)
JOIN store USING (Store_Num)
GROUP BY Emp_ID, First_Name, Last_Name, Store_Num, Store_Name)
WHERE rw = 1;
RANK为PARTITION BY中表示的每个组计算符合ORDER BY expr(几行可以具有相同排名)的每一行的等级。
分析函数在GROUP BY
之后计算答案 1 :(得分:0)
select t."Store", max("Emp. Name") keep (dense_rank first order by "Num Rentals" desc)
from (SELECT Emp_ID || ': ' || First_Name || ' ' || Last_Name AS "Emp. Name",
Store_Num || ': ' || Store_Name AS "Store",
COUNT(Emp_ID) AS "Num Rentals"
FROM Employee JOIN rental USING (Emp_ID)
JOIN store USING (Store_Num)
GROUP BY Emp_ID, First_Name, Last_Name, Store_Num, Store_Name) t;