Creazione della tabella:
CREATE TABLE VMRRTEST_DATA (
ID INTEGER,
CATG VARCHAR(30 ),
PRICE INTEGER,
DATE TIMESTAMP
)
Inserimento:
INSERT INTO VMRRTEST_DATA VALUES(1,'CAR',1000,CURRENT TIMESTAMP);
INSERT INTO VMRRTEST_DATA VALUES(2,'CAR',2000,(CURRENT TIMESTAMP)- 10 MINUTE);
INSERT INTO VMRRTEST_DATA VALUES(3,'CAR',1000,CURRENT TIMESTAMP - 20 minute);
INSERT INTO VMRRTEST_DATA VALUES(4,'CAR',30000,CURRENT TIMESTAMP);
INSERT INTO VMRRTEST_DATA VALUES(5,'CAR',5000,(CURRENT TIMESTAMP)-20 minute);
Set di risultati:
ID CATG PRICE DATE
-- ---- ----- --------------------------
1 CAR 1000 2018-10-09 22:17:59.907636
4 CAR 30000 2018-10-09 22:18:32.58254
2 CAR 2000 2018-10-09 22:30:30.875961
3 CAR 1000 2018-10-09 22:20:43.80537
5 CAR 5000 2018-10-09 22:21:14.787224
Set di risultati attesi:
RANK ID CATG PRICE DATE
---- -- ---- ----- --------------------------
1 3 CAR 1000 2018-10-09 22:20:43.80537
1 2 CAR 2000 2018-10-09 22:30:30.875961
1 5 CAR 5000 2018-10-09 22:21:14.787224
1 4 CAR 30000 2018-10-09 22:18:32.58254
Soluzione:
SELECT Rank,ID,CATG,PRICE,DATE FROM
(
SELECT
--ROW_NUMBER() OVER(ORDER BY PRICE ASC) AS RW_NM,
RANK() OVER (PARTITION BY PRICE ORDER BY DATE DESC) AS Rank,
ID,CATG,
PRICE
,DATE
FROM
VMRRTEST_DATA
--WHERE Rank
GROUP BY ID,DATE,CATG,PRICE
HAVING COUNT(*)>0
ORDER BY PRICE,DATE DESC
)
WHERE Rank = 1