在SQL Oracle中使用GROUP BY和ORDER BY的问题

时间:2015-02-03 04:20:47

标签: oracle

因此,我已被指示编写SQL查询以显示该经理的经理人编号和最低薪雇员的薪水(我在工作的数据库中有2列)。我还必须排除任何最小的群体 工资小于或等于6,000美元。按降序对输出进行排序 薪水。现在我已成功显示数据,但我似乎无法按降序排序,这就是我带到这里的原因。目前我的代码如下:

代码段#1

SELECT manager_id AS "Manager ID",
MIN(salary) AS "Lowest Paid Salary"
FROM employees
WHERE manager_id IS NOT NULL
AND salary > 6000 
GROUP BY manager_id;

这给了我以下输出: 代码片段#2

Manager ID Lowest Paid Salary
---------- ------------------
       100               6500
       147               6200
       205               8300
       108               6900
       148               6100
       149               6200
       102               9000
       101               6500
       145               7000
       146               7000

但是,我需要从Largest订购的这些值 - >最低的薪水。我试图在声明的末尾添加GROUP BY salary DESC;,这会给我以下错误:ORA-00979: not a GROUP BY expression

经过一些研究,我发现两个(GROUP BY和ORDER BY)不能在同一个查询中一起使用,因为我在GROUP BY子句中没有同时包含manager_id和salary。所以我尝试使用以下代码:

SELECT manager_id AS "Manager ID",
MIN(salary) AS "Lowest Paid Salary"
FROM employees
WHERE manager_id IS NOT NULL
AND salary > 6000 
GROUP BY manager_id, salary
ORDER BY salary DESC;

其中列出了每个manager_id的所有工资以及重复项。这不是我想要的。

我为阅读过剩而道歉,我只是想确保你知道我尝试过的以及我想要完成的事情。

所以我需要知道一种方法,我可以在同一个查询中同时使用GROUP BY和ORDER BY来显示代码片段#2但是已经订购了。或者以相同格式订购此数据的另一种方式。

提前感谢您的任何帮助/建议。

3 个答案:

答案 0 :(得分:6)

您可以按列号或列名称进行排序

SELECT manager_id AS "Manager ID",
MIN(salary) AS "Lowest Paid Salary"
FROM #employees
WHERE manager_id IS NOT NULL
AND salary > 6000 
GROUP BY manager_id
order by 2 desc


SELECT manager_id AS "Manager ID",
MIN(salary) AS "Lowest Paid Salary"
FROM #employees
WHERE manager_id IS NOT NULL
AND salary > 6000 
GROUP BY manager_id
order by "Lowest Paid Salary" desc

答案 1 :(得分:3)

您需要通过聚合函数进行排序。 ... 试试这个

SELECT manager_id AS "Manager ID",
MIN(salary) AS "Lowest Paid Salary"
FROM employees
WHERE manager_id IS NOT NULL
AND salary > 6000 
GROUP BY manager_id
ORDER BY min(salary) DESC;

答案 2 :(得分:0)

尝试: 按manager_id,工资DESC排序并删除group by子句 例如 SELECT * FROM Customers ORDER BY CustomerID DESC,CustomerName; 本声明将按照客户ID的顺序排列结果。