简体   繁体   English

如何从SQL中的表中列出3个最大的数字?

[英]How to list 3 largest numbers from table in SQL?

I'm trying to unite two bits of SQL codes and list three largest numbers from it.我试图将两位 SQL 代码结合起来,并从中列出三个最大的数字。 Here is table relation diagram这是表关系图

Query #1:查询#1:

SELECT MAX(d) AS deliveries
FROM (SELECT o.rider_id, COUNT(o.rider_id) d
FROM orders o
GROUP BY o.rider_id) AS alias; 

Query #2:查询#2:

SELECT first_name, last_name
FROM users;

My final code shows the full list of all first and second names, simply adding largest number to all of them from orders table.我的最终代码显示了所有第一个和第二个名称的完整列表,只需从orders表中将最大数字添加到所有名称中即可。 How can I modify it to make it show three names with its largest delivery count?如何修改它以使其显示具有最大交付计数的三个名称?

SELECT u.first_name, u.last_name, MAX(d) AS deliveries
FROM (SELECT o.rider_id, COUNT(o.rider_id) d
FROM orders o
GROUP BY o.rider_id) AS alias
JOIN users u
GROUP BY u.first_name, u.last_name; 

If you want exactly the top 3 (or less if there are less than 3) then use order by the attribute you want, and use limit:如果您想要前 3 个(如果少于 3 个,则更少),然后按您想要的属性使用 order,并使用 limit:

SELECT u.first_name, u.last_name, MAX(d) AS deliveries
FROM (SELECT o.rider_id, COUNT(o.rider_id) d
FROM orders o
GROUP BY o.rider_id) AS alias
JOIN users u
GROUP BY u.first_name, u.last_name
ORDER BY deliveries DESC
LIMIT 3;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM