【问题标题】:Joining a subquery using an outer column that uses a group function使用使用组函数的外部列连接子查询
【发布时间】:2021-08-10 04:02:01
【问题描述】:

所以这个对你们大多数人来说应该很简单:

我的表有一个 ID、一个 order_id 和一个状态。 同一个order_id可能有多个ID。

我需要做的是从每个 order_id 中获取最后一个 ID,这很简单:

SELECT order_id, max(ID) AS last_id 
FROM mytable
GROUP BY order_id

现在,我还需要获取与最后一个 ID 相关联的状态,所以我想做的是:

SELECT order_id, max(ID) AS last_id, x.status
FROM mytable t

LEFT JOIN (SELECT ID, status
          FROM mytable) x ON last_id = x.ID

我知道我不允许使用 last_id 别名来加入子查询,因为它说它不存在。那我该怎么办呢?

【问题讨论】:

    标签: sql postgresql join subquery


    【解决方案1】:

    您不能在查询的FROMWHERE 部分中使用别名,您应该使用max(t.ID)

    SELECT order_id, max(t.ID) AS last_id, x.status
    FROM mytable t
    
    LEFT JOIN (SELECT ID, status
              FROM mytable) x ON MAX(t.ID) = x.ID
    

    您还可以将查询包装为子查询,然后使用别名进行连接:

    SELECT t.order_id, t.last_id, x.status
    FROM (
      SELECT order_id, max(ID) AS last_id
      FROM mytable
    ) t
    LEFT JOIN mytable x
    ON t.last_id = x.ID
    

    【讨论】:

      【解决方案2】:

      另一种方法是DISTINCT ONorder_id,然后在id 上应用max()

      SELECT DISTINCT ON (order_id) 
        order_id, max(id) AS last_id,
        status
      FROM mytable 
      GROUP BY order_id,status;
      

      演示:db<>fiddle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-24
        • 2020-10-08
        • 1970-01-01
        • 1970-01-01
        • 2013-10-16
        • 1970-01-01
        • 2020-10-20
        • 1970-01-01
        相关资源
        最近更新 更多