我有這張桌子:
| 全部的 | 用戶 | 錢包 | 存盤總結 | 鏈 |
|---|---|---|---|---|
| 40 | 用戶1 | 錢包1 | 2 | 1 |
| 30 | 用戶1 | 錢包1 | 4 | 1 |
| 8 | 用戶1 | 錢包2 | 1 | 1 |
| 2 | 用戶2 | 錢包3 | 3 | 1 |
| 41 | 用戶2 | 錢包3 | 4 | 3 |
這就是我想要完成的:

Type1, Type2, n... 列是storagesummary和chain的組合
只是為了舉例:如果storagesummary == 2 和chain == 1,那么它將是 Type1。
我嘗試了這樣的方法,但我認為這不是最好的方法,我不知道如何處理用戶/錢包列:
SELECT (SELECT total from MyTable where storagesummary = 2 and chain == 1) as Total Type1 Count,
(SELECT total from MyTable where storagesummary = 4 and chain == 1) as Total Type2 Count,
.......
我不知道如何實作這一目標。
uj5u.com熱心網友回復:
這可以使用一些條件聚合來調整它。
SELECT
CONCAT(t.user, ' / ', t.wallet) AS "User Wallet Address"
, SUM(CASE
WHEN t.storagesummary = 2 AND t.chain = 1
THEN t.total
ELSE 0
END) AS "Total Type1"
, SUM(CASE
WHEN t.storagesummary = 4 AND t.chain = 3
THEN t.total
WHEN t.storagesummary = 1 AND t.chain = 1
THEN t.total
ELSE 0
END) AS "Total Type2"
, SUM(CASE
WHEN t.storagesummary IN(2,5) AND t.chain >= 2
THEN t.total
ELSE 0
END) AS "Total Type3"
FROM MyTable t
GROUP BY t.user, t.wallet
ORDER BY t.user, t.wallet
不確定您是否SUM需要MAX。
遺囑中的邏輯CASE需要更正。
但是如果你明白了這個概念,那么你就會明白要改變什么。
uj5u.com熱心網友回復:
我認為您缺少的是將內部列名與外部選擇匹配,例如:
select action_id, next_action_id from ( select action_id, lead(action_id) over (order by action_id) next_action_id from action) where action_id <> next_action_id-1;
那是為 oracle db 準備的,但是普通的 SQL 可以在沒有 next/lead 的情況下適應。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/410439.html
標籤:
下一篇:使用帶有psycopg3的Python3.9,存盤在Postgres資料庫中的混搭表情符號不會作為單個表情符號回傳。例如?????回傳??\u200d??
