[英]How do I do a DISTINCT and ORDER BY in PostgreSQL?
PostgreSQL is about to make me punch small animals. PostgreSQL将使我猛击小动物。 I'm doing the following SQL statement for MySQL to get a listing of city/state/countries that are unique. 我正在针对MySQL执行以下SQL语句,以获取唯一的城市/州/国家/地区列表。
SELECT DISTINCT city
, state
, country
FROM events
WHERE (city > '')
AND (number_id = 123)
ORDER BY occured_at ASC
But doing that makes PostgreSQL throw this error: 但是这样做会使PostgreSQL抛出此错误:
PGError: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list PGError:错误:对于SELECT DISTINCT,ORDER BY表达式必须出现在选择列表中
But if I add occured_at to the SELECT, then it kills of getting back the unique list. 但是,如果我在SELECT中添加了extended_at,那么杀死返回唯一列表的行为就很致命。
Results using MySQL and first query: 使用MySQL和第一个查询的结果:
BEDFORD PARK IL US
ADDISON IL US
HOUSTON TX US
Results if I add occured_at to the SELECT: 如果将SELECTED_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
The first set of results is what I'm ultimately trying to get with PostgreSQL. 第一组结果是我最终尝试使用PostgreSQL获得的结果。
Well, how would you expect Postgres to determine which occured_at value to use in creating the sort order? 好吧,您希望Postgres如何确定在创建排序顺序时使用哪个existed_at值?
I don't know Postgres syntax particularly, but you could try: 我不特别了解Postgres语法,但是您可以尝试:
SELECT DISTINCT city, state, country, MAX(occured_at)
FROM events
WHERE (city > '') AND (number_id = 123) ORDER BY MAX(occured_at) ASC
or 要么
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
That's assuming you want the results ordered by the MOST RECENT occurrence. 假设您希望按最近发生的结果排序结果。 If you want the first occurrence, change MAX to MIN. 如果要第一次出现,请将MAX更改为MIN。
Incidentally, your title asks about GROUP BY, but your syntax specifies DISTINCT. 顺便说一句,您的标题询问了GROUP BY,但是您的语法指定了DISTINCT。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.