如何在PostgreSQL中执行DISTINCT和ORDER BY?

时间:2009-11-03 22:13:33

标签: sql mysql database postgresql

PostgreSQL即将让我打小动物。我正在为MySQL做以下SQL语句,以获取唯一的城市/州/国家列表。

SELECT DISTINCT city
              , state
              , country 
           FROM events 
          WHERE (city > '') 
            AND (number_id = 123)  
       ORDER BY occured_at ASC

但这样做会让PostgreSQL抛出这个错误:

  

PGError:错误:对于SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中

但是如果我将occured_at添加到SELECT中,那么它就会杀死获取唯一列表。

使用MySQL和第一次查询的结果:

BEDFORD PARK       IL   US
ADDISON         IL  US
HOUSTON         TX  US

如果我将occured_at添加到SELECT:

BEDFORD PARK       IL   US  2009-11-02 19:10:00
BEDFORD PARK       IL   US  2009-11-02 21:40:00
ADDISON         IL  US  2009-11-02 22:37:00
ADDISON         IL  US  2009-11-03 00:22:00
ADDISON         IL  US  2009-11-03 01:35:00
HOUSTON         TX  US  2009-11-03 01:36:00

第一组结果是我最终试图用PostgreSQL获得的结果。

1 个答案:

答案 0 :(得分:6)

那么,您希望Postgres如何确定在创建排序顺序时使用哪个occured_at值?

我不太了解Postgres的语法,但你可以试试:

SELECT DISTINCT city, state, country, MAX(occured_at)
       FROM events 
      WHERE (city > '') AND (number_id = 123) ORDER BY MAX(occured_at) ASC

SELECT city, state, country, MAX(occured_at)
       FROM events 
      WHERE (city > '') AND (number_id = 123) 
      GROUP BY city, state, country ORDER BY MAX(occured_at) ASC

假设您希望MOST RECENT出现时排序的结果。如果您想要第一次出现,请将MAX更改为MIN。

顺便提一下,您的标题询问GROUP BY,但您的语法指定了DISTINCT。