1

我正在尝试将 ROW_NUMBER()... 设置为别名,以便可以在 OFFSET 中引用它。例如OFFSET some_alias - 1。我需要从更大的查询中获取包含 ROW_NUMBER() 的单行。这是我的工作代码(得到正确的 ROW_NUMBER(),但没有被正确的数量抵消):

WITH FirstQuery AS (
    SELECT "RepInitials", COUNT("OrderStatus"), ROW_NUMBER()OVER(ORDER BY COUNT("OrderStatus") DESC)
    FROM "tblBulkSalesQuery"
    WHERE "OrderStatus" = 'CMC'
    GROUP BY "RepInitials"
)
SELECT "RepInitials", COUNT("OrderStatus"), ROW_NUMBER()OVER(ORDER BY COUNT("OrderStatus") DESC)
    FROM "tblBulkSalesQuery"
    WHERE "OrderStatus" = 'CMC'
    GROUP BY "RepInitials"
    LIMIT 1
    OFFSET 1;
4

1 回答 1

2
select *
from (
    SELECT "RepInitials", 
           COUNT("OrderStatus") as order_status_count, 
           ROW_NUMBER() OVER (ORDER BY COUNT("OrderStatus") DESC) as rn
    FROM "tblBulkSalesQuery"
    WHERE "OrderStatus" = 'CMC'
    GROUP BY "RepInitials"
) as t
where rn = 1

编辑

t是嵌套选择(“派生表”)的别名。PostgreSQL 要求每个派生表都有自己的“名称”,而这只能通过分配别名来完成。

它几乎与以下内容相同:

with t as (
  ... here goes the real select ...
)
select *
from t 
where rn = 1;
于 2012-11-26T14:00:59.740 回答