假设我有一个包含3列的表:
我想显示以下内容:
附加要求是具有最大销售额的公司(所有部门)首先显示,其余结果相应地排序。
我将如何编写查询?
我尝试过以下操作,但它不起作用:
SELECT t1.company,
cs1.deparment,
SUM(cs1.sales)
FROM company_sales cs1,
(SELECT cs2.company,
SUM(cs2.sales)
FROM company_sales cs2
WHERE cs2.company IS NOT NULL
GROUP BY cs2.company
ORDER BY 2 DESC) t1
WHERE cs1.company = t1.company
GROUP BY t1.company,
cs1.deparment;
答案 0 :(得分:2)
您可以使用窗口功能执行此操作:
select company, department, sum(sales)
from t
group by company, department
order by sum(sum(sales)) over (partition by company) desc, company;
您还可以在select
子句中包含表达式,以查看整个公司的销售总额。
答案 1 :(得分:0)
尝试:
SELECT company,department,sum(sales)
FROM table GROUP BY company,department
ORDER BY Max(sales)