我正在尋找一種更有效的方法來完成我已經用幾個不同的 SQL 陳述句解決的問題。
問題:
我有兩張桌子
- 事務表,以及
- 帳戶表
該transactions表具有如下所示的列:
| acct_sending | acct_receiving | 數量 | tx_datetime |
|---|---|---|---|
| 100 | 101 | 10 | yyyy-mm-dd hh-mm-ss |
| 101 | 100 | 5 | yyyy-mm-dd hh-mm-ss |
| 101 | 200 | 1 | yyyy-mm-dd hh-mm-ss |
| 200 | 101 | 11 | yyyy-mm-dd hh-mm-ss |
| 200 | 234 | 22 | yyyy-mm-dd hh-mm-ss |
| 234 | 567 | 24 | yyyy-mm-dd hh-mm-ss |
| 567 | 890 | 56 | yyyy-mm-dd hh-mm-ss |
| 890 | 100 | 73 | yyyy-mm-dd hh-mm-ss |
該accounts表具有如下所示的列:
| 帳戶 | 平衡 | 上次發送 |
|---|---|---|
| 100 | 10 | yyyy-mm-dd hh-mm-ss |
| 101 | 100 | yyyy-mm-dd hh-mm-ss |
| 102 | 100 | yyyy-mm-dd hh-mm-ss |
| 200 | 1000 | yyyy-mm-dd hh-mm-ss |
| 234 | 10000 | yyyy-mm-dd hh-mm-ss |
| 567 | 1000 | yyyy-mm-dd hh-mm-ss |
| 890 | 100 | yyyy-mm-dd hh-mm-ss |
我想創建一個查詢,該查詢回傳一個事務串列,其中acct_sending和acct_receiving都在accounts表中并且具有balance大于某個值的值。如果查詢結果有一列包含這兩個帳戶之間的交易總數,則獎勵積分。count
給定上面的transactions和accounts表,如果我們運行這個查詢,balance > 10那么結果將是:
| acct_sending | acct_receiving | 數數 |
|---|---|---|
| 101 | 200 | 2 |
| 200 | 234 | 1 |
| 234 | 567 | 1 |
| 567 | 890 | 1 |
---
我的解決方案
首先,創建一個帶有事務的臨時表,其中acct_sending = account和account > 10
CREATE TEMP TABLE temp_sending AS
SELECT acct_sending, acct_receiving
FROM transactions t
WHERE EXISTS
(SELECT account
FROM accounts a
WHERE t.acct_sending = a.account AND a.balance > 10)
然后,使用最后一個臨時表創建一個新的臨時表,其中acct_receiving = account和account > 10
CREATE TEMP TABLE temp_sending_receiving AS
SELECT acct_sending, acct_receiving
FROM temp_sending t
WHERE EXISTS
(SELECT account
FROM accounts a
WHERE t.acct_sending = a.account AND a.balance > 10)
最后,我查詢temp_sending_receiving以獲取唯一交易串列,并生成該count列。
SELECT acct_sending, account_receiving, count(*)
FROM (
SELECT
CASE WHEN sender < receiver THEN sender ELSE receiver END AS sender,
CASE WHEN sender < receiver THEN receiver ELSE sender END AS receiver
FROM temp_sending_receiving
) AS x
GROUP BY acct_sending, account_receiving
運行這些查詢中的每一個都會給我想要的結果,但是......
有沒有更好/更有效的方法來做到這一點?
我正在考慮查詢時間和記憶體效率。謝謝!!!
---
筆記
我在 DBeaver 和 Python 中將這些 SQL 查詢作為腳本運行,所以我將它們添加為標簽。如果那是錯誤的,LMK!謝謝。:)
uj5u.com熱心網友回復:
您必須加入transactions2 個副本accounts并匯總:
SELECT MIN(t.acct_sending, t.acct_receiving) sender,
MAX(t.acct_sending, t.acct_receiving) receiver,
COUNT(*) count
FROM transactions t
INNER JOIN accounts a1 ON a1.account = t.acct_sending AND a1.balance > 10
INNER JOIN accounts a2 ON a2.account = t.acct_receiving AND a2.balance > 10
GROUP BY sender, receiver;
或者,使用CTE:
WITH cte AS (SELECT * FROM accounts WHERE balance > 10)
SELECT MIN(t.acct_sending, t.acct_receiving) sender,
MAX(t.acct_sending, t.acct_receiving) receiver,
COUNT(*) count
FROM transactions t
INNER JOIN cte c1 ON c1.account = t.acct_sending
INNER JOIN cte c2 ON c2.account = t.acct_receiving
GROUP BY sender, receiver;
請參閱演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527248.html
上一篇:我的表包含不應為空的可為空值
