如何编写SQL返回profit_by_sales_rep表总利润最高的销售代表数据
问题原因分析
你编写的SQL中使用了GROUP BY sales_rep_first_name, sales_rep_last_name,会将表中数据按销售代表拆分分组,MAX(total_profit)实际计算的是每个销售代表自身的最高利润值,而profit_by_sales_rep本身已经是按销售代表聚合后的统计表,每行对应一个销售代表的利润数据,所以分组后会返回全量销售代表的结果,和需求不符。
正确实现方案
核心逻辑是将所有销售代表按总利润降序排序,取排序后的第一条结果即可,不同数据库的语法略有差异:
适配MySQL/PostgreSQL等支持LIMIT语法的数据库
SELECT sales_rep_first_name, sales_rep_last_name, total_profit FROM profit_by_sales_rep ORDER BY total_profit DESC LIMIT 1;
适配SQL Server数据库
SELECT TOP 1 sales_rep_first_name, sales_rep_last_name, total_profit FROM profit_by_sales_rep ORDER BY total_profit DESC;
适配Oracle数据库
SELECT sales_rep_first_name, sales_rep_last_name, total_profit FROM profit_by_sales_rep ORDER BY total_profit DESC FETCH FIRST 1 ROW ONLY;
如果需要处理多个销售代表总利润并列最高的场景,可以在ORDER BY后额外加排序规则(比如按姓氏字母升序排序),保证返回结果的唯一性:
-- 示例:并列时按姓氏升序排序取第一个 SELECT sales_rep_first_name, sales_rep_last_name, total_profit FROM profit_by_sales_rep ORDER BY total_profit DESC, sales_rep_last_name ASC LIMIT 1;
内容的提问来源于stack exchange,提问作者Timothy Clotworthy
相关产品推荐
相关产品推荐

