使用postgres,我想检索每个不同的包,但检索每个组的最新包。
例如,我将此表命名为products:
package_name price date
- | 52500.0 | 20080910
- | 52900.0 | 20090422
- | 52900.0 | 20090706
ELITE PACKAGE | 62200.0 | 20080910
ELITE PACKAGE | 62500.0 | 20090706
ELITE PACKAGE | 62500.0 | 20090422
TECH PACKAGE | 57200.0 | 20080910
TECH PACKAGE | 58200.0 | 20090706
TECH PACKAGE | 58200.0 | 20090422
我想用SQL查询得到以下结果:
- | 52900.0 | 20090706
ELITE PACKAGE | 62500.0 | 20090706
TECH PACKAGE | 58200.0 | 20090706
我已经尝试了一些(我认为)可以在mySQL中运行的东西,但是我无法将其用于postgres。
是否有可能做到,我该怎么做?
谢谢,
斯蒂芬妮
答案 0 :(得分:5)
避免自我加入的另一种选择(我总是讨厌自我加入)
SELECT package_name,price,date FROM
(
SELECT package_name,price,date,
ROW_NUMBER() OVER (PARTITION BY package_name ORDER BY date DESC) as rw
FROM products
) a
WHERE rw=1;
答案 1 :(得分:3)
SELECT t.package_name, p.price, t.MaxDate
FROM (SELECT package_name, MAX(date) AS MaxDate
FROM products
GROUP BY package_name) t
INNER JOIN products p
ON t.package_name = p.package_name
and t.MaxDate = p.date