我在處理 Select 中的某些資訊時遇到問題。我嘗試了幾種方法,但沒有積極的結果。
選擇:
select
cpri.sequential,
cpri.id,
coalesce(sum(pdr.something), 0) something,
...
from
cpri
inner join cpr on cpr.id = cpri.id
left join pdr on pdr.other_id = cpr.other_id
where
...
group by
cpri.sequential,
cpri.id,
...
order by
cpri.id desc
我今天的輸出如下:
sequential|id |something|other_information
2637|880| 15000.00| ...
2635|880| 15000.00| ...
2636|880| 15000.00| ...
2638|880| 15000.00| ...
2624|876| 6000.00| ...
2625|876| 6000.00| ...
2611|870| 2000.00| ...
2612|870| 2000.00| ...
2613|870| 2000.00| ...
2614|870| 2000.00| ...
2571|858| 5000.00| ...
2572|858| 5000.00| ...
2569|858| 5000.00| ...
2570|858| 5000.00| ...
133| 68| 6366.90| ...
134| 68| 6366.90| ...
130| 66| 120.00| ...
129| 66| 120.00| ...
目標輸出:
sequential|id |something|other_information
2637|880| 15000.00| ...
2635|880| 0.00| ...
2636|880| 0.00| ...
2638|880| 0.00| ...
2624|876| 6000.00| ...
2625|876| 0.00| ...
2611|870| 2000.00| ...
2612|870| 0.00| ...
2613|870| 0.00| ...
2614|870| 0.00| ...
2571|858| 5000.00| ...
2572|858| 0.00| ...
2569|858| 0.00| ...
2570|858| 0.00| ...
133| 68| 6366.90| ...
134| 68| 0.00| ...
130| 66| 120.00| ...
129| 66| 0.00| ...
如果我們將每個相等的“id”分成組,“something”列必須僅在第一行有其值,而在其他行中它必須為零。
有沒有辦法做到這一點?
uj5u.com熱心網友回復:
您可以通過使用 row_number 的 case 運算式來執行此操作,例如:
case when Row_Number() over(partition by cpri.id order by cpri.sequential) = 1
then coalesce(sum(pdr.something), 0) else 0
end something
uj5u.com熱心網友回復:
您可以使用分析函式 row_number:
with request as (
select req.* ,
/******************/
ROW_NUMBER() OVER (PARTITION BY id ORDER BY something) as row_nbr
from (
select
cpri.sequential,
cpri.id,
coalesce(sum(pdr.something), 0) something,
...
from
cpri
inner join cpr on cpr.id = cpri.id
left join pdr on pdr.other_id = cpr.other_id
where
...
group by
cpri.sequential,
cpri.id,
) as res
)
select sequential , id , case when row_nbr = 1 then something ;
欲了解更多資訊: https ://www.postgresql.org/docs/current/tutorial-window.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511353.html
上一篇:如何從表中檢索資料并使用Python和Django在html檔案中顯示?
下一篇:API中的分頁和串列
