postgresql中的问题分组

postgresql中的问题分组,sql,postgresql,group-by,Sql,Postgresql,Group By,假设我创建了一个“订单”表,如下所示: CREATE TABLE orders (id SERIAL, customerID INTEGER, timestamp BIGINT, PRIMARY KEY(id)); 时间戳是UNIX时间戳。现在我想为每个客户选择最新订单的ID。因为风景会很好 然而,以下声明 CREATE VIEW lastOrders AS SEL

假设我创建了一个“订单”表,如下所示:

CREATE TABLE orders (id SERIAL, 
                     customerID INTEGER,
                     timestamp BIGINT, 
                     PRIMARY KEY(id));
时间戳是UNIX时间戳。现在我想为每个客户选择最新订单的ID。因为风景会很好

然而,以下声明

CREATE VIEW lastOrders AS SELECT  id,
                                  customerID, 
                                  MAX(timestamp) 
                                  FROM orders 
                                  GROUP BY customerID;
导致postgre错误:

错误:列“orders.id”必须出现在分组依据中 子句或可在聚合函数中使用


我做错了什么?

kquinns的答案将修复异常,但这不是您想要的

我不知道mysql的功能,但类似这样的东西可以用于oracle:

select a.*
from 
    orders a, 
    (select customerID, max(timestamp) timestamp 
        from orders group by customerID
    ) b
where a.customer_id = b.customerID
and a.timestamp = b.timestamp

实际上,oracle可以使用分析函数,但我认为mysql中没有这些函数。对于这类事情,可以使用两种方法。Jens已经展示了一个

另一种是使用“DISTINCT ON”子句:


下面的查询应该只返回每个客户的最后一个订单

CREATE  VIEW last_orders AS
SELECT  id, customer_id, timestamp
FROM    orders AS o
WHERE   timestamp = (
            SELECT  MAX(timestamp)
            FROM    orders AS oi
            WHERE   o.customer_id = oi.customer_id
        );
(假设一个客户不能有两个时间戳值完全相同的订单。)


编辑:Postgres的
与众不同的
是一种更巧妙的方法。我很高兴我知道了。但是,上述内容适用于其他RDBMS。

仅供参考:海报中提到了postgresql。两种输入错误:在max(时间戳)和timestamp之间缺少“AS”,并且a.customer_id应替换为postgres doc中的a.customerIDlooked。正是我需要的。非常优雅。谢谢我同意。这种事情一次又一次地出现,Postgres的开发人员找到了一种很好的处理方法。可惜它不是标准SQL的一部分。
CREATE  VIEW last_orders AS
SELECT  id, customer_id, timestamp
FROM    orders AS o
WHERE   timestamp = (
            SELECT  MAX(timestamp)
            FROM    orders AS oi
            WHERE   o.customer_id = oi.customer_id
        );