我有一份employee_sale表
id product quantity
3 y 6
1 x 2
1 y 5
2 x 4
3 x 3
3 y 5
3 X 5
4 y 3
4 y 4
我想选择所有产品的员工ID,产品和第二最大数量列表。
请帮助必要的SQL查询
感谢
答案 0 :(得分:1)
我会使用rank()
函数:
SELECT id, product, quantity
FROM (SELECT id, product, quantity,
RANK() OVER (PARTITION BY id, product ORDER BY quantity DESC)
AS rk
FROM employee_sale)
WHERE rk = 2
答案 1 :(得分:1)
两种选择:
使用ROW_NUMBER()
:
SELECT id,product,quantity FROM
(SELECT *,ROW_NUMBER() OVER(PARTITION BY product ORDER BY quantity DESC) as RN
FROM employee_sale) T
WHERE RN=2
使用RANK()
:
SELECT id,product,quantity FROM
(SELECT *, RANK() OVER (PARTITION BY product ORDER BY quantity DESC) as Rnk
FROM employee_sale) T
WHERE Rnk=2
结果:
ID PRODUCT QUANTITY
2 x 4
1 y 5