在orderby中使用别名时如何获取行号

How to get the row number when using alias in orderby

我有一个问题。我在使用 row_number 时按顺序使用了别名,我得到了

[42703] ERROR: column "total_comments" does not exist error Position: 335

我该如何解决这个问题?

 select
      cr_seller_history_id,
      c.created_at,
      company_name,
      business_name,
      brand,
      kep_mail,
      address,
      phone,
      mail,
      slug,
      name,
      point,
      contact_positive,
      contact_negative,
      product_number,
      (product_positive + product_negative) as total_comments,
      ROW_NUMBER() OVER(ORDER BY total_comments) as rank
    from cr_companies a
      INNER JOIN cr_sellers b ON a.cr_company_id = b.cr_company_id
      INNER JOIN cr_seller_histories c ON b.cr_seller_id = c.cr_seller_id
      WHERE DATE(c.created_at) = DATE 'yesterday'
    ORDER BY total_comments DESC NULLS LAST

问题出在:

ROW_NUMBER() OVER(ORDER BY total_comments) as rank

你不能像这样使用别名 - order by 在 select 中接受别名,在 window 函数中不接受别名:

https://www.postgresql.org/docs/current/static/sql-select.html#SQL-SELECT-LIST

An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.

改为尝试:

ROW_NUMBER() OVER(ORDER BY (product_positive + product_negative)) as rank

或使用子查询 - 然后可以在 window 函数中使用别名

其他解决方案是子查询、CTE 或横向连接。所以,你可以这样写:

select . . . 
      v.total_comments,
      row_number() over (order by v.total_comments) as rank
from cr_companies c join
     cr_sellers s
     on c.cr_company_id = s.cr_company_id join
     cr_seller_histories sh
     on s.cr_seller_id = sh.cr_seller_id, lateral
     (values (product_positive + product_negative)) v(total_comments)
where DATE(c.created_at) = date 'yesterday'
order by v.total_comments desc nulls last;

请注意,我还将 table 别名更改为 table 名称的缩写。这是最佳做法,可以更轻松地编写、读取和修改查询。