我有一個使用多個連接的 PostgreSQL 和一個作為計算結果的列。從該查詢的結果中,我需要提取該列最大的行,并且可能有很多行。如果沒有,我可以ORDER BY that_column DESC LIMIT 1;我發現如果我只需要在現有的資料庫表上使用它,我可以這樣做:
SELECT columns FROM table_name
WHERE that_coulmn = (SELECT MAX(that_column) FROM table_name)
然而,事實也并非如此。我有一個這樣的查詢:
SELECT z.xyz, (x.aa- x.bb) * y.qq as that_column
FROM table_1 x
JOIN table_2 y ON x.foo = y.foo
JOIN table_3 z ON y.bar = z.bar
JOIN table_4 w ON w.baz = z.baz
where x.aa IS NOT NULL
現在,這有效。現在我需要知道如何將其作為子查詢并從中獲取最大z.xyz的行that_column。有什么幫助嗎?
uj5u.com熱心網友回復:
也許是這個?
SELECT MAX(thatmax.that_column) as theMax FROM (
SELECT z.xyz, (x.aa- x.bb) * y.qq as that_column
FROM table_1 x
JOIN table_2 y ON x.foo = y.foo
JOIN table_3 z ON y.bar = z.bar
JOIN table_4 w ON w.baz = z.baz
where x.aa IS NOT NULL
) thatmax
uj5u.com熱心網友回復:
如果您需要選擇其他列作為輸出:
select * from (
select *, dense() over(order by (x.aa- x.bb) * y.qq desc) as that_column
from table_1 x
join table_2 y ON x.foo = y.foo
join table_3 z ON y.bar = z.bar
join table_4 w ON w.baz = z.baz
where x.aa IS NOT NULL
) t where that_column = 1
uj5u.com熱心網友回復:
我找到了!
我把它當作一個子查詢,使用rank按 thatColumn 進行排名,然后把它放在另一個子查詢中以獲取 rank=1 的那些
SELECT xyz FROM (
xyz, thatColumn, RANK() OVER(ORDER BY thatColumn DESC) FROM (
-- the subqery in the question
)
) as highest_and_rank
WHERE thatColumnRank=1
感謝所有試圖提供幫助的人。你真棒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/370190.html
標籤:sql PostgreSQL的 子查询 总计的 聚合函数
