我正在尝试将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;
答案 0 :(得分: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;