我想选择具有row
的整个min price
。因为我需要更多列的数据来显示哪个具有最低价格。像下面的东西。
SELECT ep.*, min(ep.price) minprice FROM Equip_price ep;
如何完成Oracle DB?
我实际上想通过equipment_id获取equipment_price。 以下是样本数据。
pid equipmentID price
1 1 50
2 2 20
3 1 100
4 1 20
5 3 100
6 3 10
7 1 20
我希望结果如此。 (按设备ID的最低价格组)
id equipmentID price
4 1 20
2 2 20
6 3 10
答案 0 :(得分:1)
更新具体答案:
SQL> WITH Equip_price AS
2 ( SELECT 1 pid, 1 equipmentID, 50 price FROM dual
3 UNION ALL
4 SELECT 2 , 2 , 20 FROM dual
5 UNION ALL
6 SELECT 3 , 1 , 100 FROM dual
7 UNION ALL
8 SELECT 4 , 1 , 20 FROM dual
9 UNION ALL
10 SELECT 5 , 3 , 100 FROM dual
11 UNION ALL
12 SELECT 6 , 3 , 10 FROM dual
13 UNION ALL
14 SELECT 7 , 1 , 20 FROM dual
15 )
16 SELECT ep.pid,
17 ep.equipmentID,
18 ep.price
19 FROM (
20 SELECT ep.*,
21 row_number() OVER(PARTITION BY ep.equipmentID ORDER BY ep.price)
22 AS row_identifier
23 FROM Equip_price ep
24 ) ep
25 WHERE ep.row_identifier = 1;
PID EQUIPMENTID PRICE
---------- ----------- ----------
4 1 20
2 2 20
6 3 10
SQL>
例如,要获得每个部门最低工资的员工详细信息 -
SQL> WITH DATA AS
2 ( SELECT deptno, MIN(sal) min_sal FROM emp GROUP BY deptno
3 )
4 SELECT * FROM emp A, DATA b
5 WHERE A.deptno = b.deptno
6 AND A.sal = b.min_sal
7 /
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO DEPTNO MIN_SAL
---------- ---------- --------- ---------- --------- ---------- ---------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20 20 800
7900 JAMES CLERK 7698 03-DEC-81 950 30 30 950
7934 MILLER CLERK 7782 23-JAN-82 1300 10 10 1300
您还可以使用分析功能,例如 ROW_NUMBER 。
SQL> WITH DATA AS
2 ( SELECT t.*, row_number() OVER(ORDER BY sal) rn FROM emp t
3 )
4 SELECT * FROM emp WHERE empno =
5 (SELECT empno FROM data WHERE rn = 1
6 )
7 /
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7369 SMITH CLERK 7902 17-DEC-80 800 20
SQL>
没有CTE:
SELECT E.*
FROM Equip_price E
INNER JOIN (
SELECT ep.equipmentID, min(ep.price) minprice
FROM Equip_price ep
GROUP BY ep.equipmentID
) aggr
ON (E.equipmentID = aggr.equipmentID AND E.price = aggr.minprice)
OR
SELECT ep.id,
ep.equipmentID,
ep.price
FROM (
SELECT ep.*,
row_number() OVER(PARTITION BY ep.equipmentID ORDER BY ep.price)
AS row_identifier
FROM Equip_price ep
) ep
WHERE ep.row_identifier = 1;
答案 1 :(得分:0)
试试这个:
select min(x.pid) as min_pid, x.equipmentID, y.min_price
from Equip_price x
inner join
(
select equipmentID, min(price) as min_price
from Equip_price
group by equipmentID
) y on y.equipmentID = x.equipmentID and y.min_price = x.price
group by x.equipmentID, y.min_price
order by 2;