请问,如果不使用MIN / MAX功能,如何从选择中得到相同的结果? 我需要表venda的vendor_nome和最高的venda_valor
CREATE TABLE Vendedor(vendedor_id integer, vendedor_nome text);
CREATE TABLE Venda(venda_id integer, vendedor_id integer,vendedor_data date,
venda_valor double);
INSERT INTO Vendedor VALUES(1,'Joao');
INSERT INTO Vendedor VALUES(2,'Maria');
INSERT INTO Vendedor VALUES(3,'Pedro');
INSERT INTO Venda VALUES(1,1,'2016-01-01',5000);
INSERT INTO Venda VALUES(2,1,'2016-08-01',2000);
INSERT INTO Venda VALUES(3,1,'2017-01-01',10000);
INSERT INTO Venda VALUES(4,2,'2016-02-02',15000);
INSERT INTO Venda VALUES(5,2,'2016-01-01',9000);
INSERT INTO Venda VALUES(6,2,'2017-01-01',12000);
INSERT INTO Venda VALUES(7,3,'2016-08-01',1000);
INSERT INTO Venda VALUES(8,3,'2017-03-30',15000);
INSERT INTO Venda VALUES(9,3,'2017-09-08',25000);
SELECT A.VENDEDOR_NOME, MAX(venda_valor)
FROM Vendedor as A
LEFT JOIN Venda as B ON (A.VENDEDOR_ID = B.VENDEDOR_ID)
WHERE B.vendedor_data between '2016-01-01' and '2016-12-31'
GROUP BY 1;
答案 0 :(得分:1)
使用窗口功能:
select v.vendedor_nome, ve.*
from venedor v left join
(select ve.*,
row_number() over (partition by ve.vendedor_id order by ve.venda_valor desc) as seqnum
from venda ve
) ve
on ve.vendedor_id = v.vendedor_id and ve.seqnum = 1;