【问题标题】:Why can't i limit my rank()?为什么我不能限制我的排名()?
【发布时间】:2016-06-15 05:51:45
【问题描述】:

我正在尝试对排名功能进行限制,但我似乎无法使其发挥作用。我错过了什么?到目前为止,我在外部查询上使用了 WHERE/HAVING 函数:WHERE rank ,但我收到没有 Rank Column 的错误。

我一直在环顾四周,许多人也使用了别名。

    SELECT a.customer_name ,
       a.unit ,
       sum(a.price) - sum(b.price) AS "highest revenue" ,
       rank() over (partition BY a.unit
                    ORDER BY sum(a.price) - sum(b.price) DESC) AS "Rank"
FROM
  (SELECT customer_name ,
          unit ,
          price
   FROM table1
   WHERE booked BETWEEN '12/01/15' AND '12/31/15') a
JOIN
  (SELECT customer_name ,
          unit ,
          price
   FROM table1
   WHERE booked BETWEEN '11/01/15' AND '11/30/15') b ON a.unit = b.unit
GROUP BY a.customer_name,
         a.unit
ORDER BY a.unit,
         sum(a.price) - sum(b.price) DESC, rank() over (partition BY a.unit ORDER BY sum(a.price) - sum(b.price) DESC) DESC

【问题讨论】:

    标签: postgresql greatest-n-per-group rank window-functions


    【解决方案1】:

    您不能在查询本身中使用别名,您应该将其全部包装在外部查询中:

    SELECT customer_name, unit, "highest revenue", rank
    FROM (
      SELECT a.customer_name, a.unit,
             sum(a.price - b.price) AS "highest revenue",
             rank() OVER (PARTITION BY a.unit
                          ORDER BY sum(a.price - b.price) DESC) AS rank
      FROM
        (SELECT customer_name, unit, price
         FROM table1
         WHERE booked BETWEEN '12/01/15' AND '12/31/15') a
      JOIN
        (SELECT customer_name, unit, price
         FROM table1
         WHERE booked BETWEEN '11/01/15' AND '11/30/15') b USING (unit)
      GROUP BY a.customer_name, a.unit) sub
    ORDER BY unit, "highest revenue" DESC, rank DESC;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多