[英]I am having trouble joining these two results in one query
銀行交易轉錄客戶請求查詢其網上銀行 web 服務中的儀表板。 它應該返回所有客戶帳戶的列表並獲取他們當月的交易。
結果應包含以下列:iban/transactions/total
-iban:賬戶iban
-transactions: 特定賬戶的交易金額記錄列表 iban:
-total:交易總金額
結果應按交易總數降序排序,然后按總數降序排序。
筆記:
- 結果中應僅包含當月的交易。
-當前月份是九月。
-ID為INT主鍵,Iban為varchar,account_id為INT外鍵(id),dt為datetime,amount為varchar
我是新手,所以這里是我可以放在最好的參考示例:
Accounts
ID iban
1 GT92 GJH2 AYZM
2 MT82 GWLY FWMY
3 GI36 YOPG Y6NQ
Transactions
account_id dt amount
1 2022-08-25 13:59:30 $42.87
1 2022-08-26 19:12:32 $24.04
1 2022-09-05 17:35:29 $70.07
1 2022-09-10 13:09:40 $26.15
1 2022-09-13 16:28:55 $10.15
2 2022-08-26 05:05:38 $82.83
2 2022-09-03 05:12:33 $34.14
2 2022-09-03 17:19:27 $94.94
2 2022-09-04 10:36:07 $69.31
2 2022-09-12 05:15:22 $90.06
2 2022-09-18 14:30:52 $54.85
3 2022-09-25 04:28:37 $45.99
3 2022-08-22 21:12:42 $65.98
3 2022-08-29 04:45:23 $10.99
3 2022-09-02 09:32:25 $98.36
3 2022-09-02 14:58:25 $25.45
3 2022-09-06 21:15:47 $57.98
3 2022-09-10 10:25:26 $37.90
我嘗試使用 STUFF 和 XML PATH 進行貨幣轉換以獲得特定 ID 的總和,但無法在單個查詢中獲得結果
select iban,
STUFF((select '+' +amount from transactions where account_id = id
for XML PATH('')),1,1,'')[transactions]
from Accounts
order by id;
select
SUM((case when isnumeric([amount])=1 then convert(money,[amount]) else 0 end)) as Transactions from transactions
group by account_id;
在 ID 和 account_id 字段上嵌套聚合查詢和 JOIN。 這意味着在聚合查詢中選擇 account_id。 此外,在聚合查詢中包括記錄計數。 在 STUFF() SQL 中包含ORDER BY dt
。
SELECT iban, TransTotal,
STUFF((SELECT '+' +amount FROM transactions WHERE account_id = id ORDER BY dt
FOR XML PATH('')),1,1,'')[transactions]
FROM Accounts INNER JOIN (SELECT account_id, Count(account_id) AS TransCount
SUM((CASE WHEN isnumeric([amount])=1 THEN convert(money,[amount]) ELSE 0 END)) AS TransTotal
FROM transactions
GROUP BY account_id) AS T
ON Accounts.id = T.account_id
ORDER BY TransCount DESC, TransTotal DESC;
在 STUFF 和聚合查詢中添加年/月的過濾條件。 Format() function 是一種方式。
Format(dt, 'yyyyMM') = Format(GetDate(), 'yyyyMM')
代替 GetDate(),可以使用 static 參數或由用戶輸入。
另一種方法:
SELECT iban, Transactions, TransTotal FROM Accounts INNER JOIN
(SELECT account_id, Count(account_id) AS TransCount,
STRING_AGG(amount, '+') WITHIN GROUP (ORDER BY dt) AS Transactions,
SUM((CASE WHEN isnumeric([amount])=1 THEN convert(money,[amount]) ELSE 0 END)) AS TransTotal
FROM transactions
WHERE Format(dt, 'yyyyMM')=Format(GetDate(), 'yyyyMM')
GROUP BY account_id) AS T
ON Accounts.id = T.account_id
ORDER BY TransCount DESC, TransTotal DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.