开发者

Get the newest entry before a GROUP BY query

Using postgres, I would like to retrieve each different packages, but retrieve the most recent package for each group.

For example, I have this table named products:

package_name        price           date
-               |   52500.0 |   20080910
-               |   52900.0 |   2009042开发者_C百科2
-               |   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

And I would like to get the following result with a SQL query:

-                   |   52900.0 |   20090706
ELITE PACKAGE       |   62500.0 |   20090706
TECH PACKAGE        |   58200.0 |   20090706

I have tried a couple of things that (I think) would have worked in mySQL, but I can't get it right for postgres.

Is it something possible to do, and how would I do it?

Thanks,

Stephanie


Another option that avoids the self join (I always hate self joins)

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;


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜