我正在尝试计算按月分组的每日平均交易的平均值。
我有以下交易表:
交易表
我想得到以下结果:
结果表
Average_Amount_Credited =(每月Amount_Credited总数/每月天数)/使用月数
Average_Amount_Debited =(每月Amount_Debited总和/每月天数)/使用月数
为了得出结果表,我使用30作为每月的天数。
我还想计算每个月balance amount(Amount_Credited - Amount_Debited)
为正或负的次数,如结果表所示。
以下是我使用的查询:
SELECT
"T"."ID",
date_trunc('month',"T"."Date_Transaction") AS "PERIOD",
SUM(COALESCE("T"."Amount_Credited",0))/30 AS "Average Amount_Credited",
SUM(COALESCE("T"."Amount_Debited",0))/30 AS "Average Amount_Debited",
(CASE WHEN (SUM(COALESCE("T"."Amount_Credited",0))/30 - SUM(COALESCE("T"."Amount_Debited",0))/30) >0
THEN '1'
WHEN (SUM(COALESCE("T"."Amount_Credited",0))/30 - SUM(COALESCE("T"."Amount_Debited",0))/30) <0
THEN '0'
END) "Status Balance"
FROM "Transaction" "T"
WHERE "T"."ID" = '1'
GROUP BY "T"."ID", date_trunc('month',"T"."Date_Transaction")
正如您将通过我的查询看到它每月返回一行但我想按ID返回一行,显示不同期间平均值的平均值。