[英]Joining on the same table to get 2 different amount values
我想根據 2 個不同的帳戶代碼(1301 和 1300)獲取資金來源(dim_6)的總金額。
下面是我設計的查詢。
SELECT t.dim_6,sum(t.amount) as bvalue, sum(t1.amount) as b1value
FROM agltransact t
LEFT OUTER JOIN agltransact t1 ON t.dim_6 =t1.dim_6
WHERE
t.dim_6 ='AWD-000261' and t1.dim_6='AWD-000261' and (t.period between '201801' and '202102') and (t1.period between '201801' and '202102')
and t.account = '1300' and t.voucher_type!='YE'
and t1.account = '1301' and t1.voucher_type!='YE'
如果我嘗試對 1 個帳戶代碼運行簡單的 SQL 查詢,則上述查詢不會返回正確的金額總和,並且與金額的值不匹配,如下所示
select dim_6,sum(amount) from agltransact where dim_6= 'AWD-000261' and voucher_type!='YE' and period between '201801' and '202102' and account ='1300' group by dim_6
上述兩個查詢具有相同的條件,但如果我加入,金額值不匹配。
我錯過了什么?
我想根據 2 個不同的帳戶代碼(1301 和 1300)獲取資金來源(dim_6)的總金額。
只需使用條件聚合:
下面是我設計的查詢。
SELECT t.dim_6,
SUM(CASE WHEN t.account = '1300' THEN t.amount END) as value_1300,
SUM(CASE WHEN t.account = '1301' THEN t.amount END) as value_1301
FROM agltransact t
WHERE t.dim_6 = 'AWD-000261' AND
(t.period between '201801' and '202102') AND
t.voucher_type <> 'YE' AND
t.account IN ('1300', '1301')
GROUP BY dim_6;
注意:我提供答案是因為我認為這是一個比其他答案更好的解決方案。
您的查詢不起作用的原因是假設來自t
的預期記錄是1
並且來自t2
是2
那么您將總共有2
行,它將從t
重復記錄兩次。 因此, sum(t.amount)
將計算兩次而不是一次。 因此,您得到的值不正確。
您需要分別運行這兩個查詢並組合結果,如下所示。 我為此使用了CTE 。
;WITH t AS (
select dim_6, sum(amount) as amount
from agltransact
where dim_6= 'AWD-000261'
and voucher_type!='YE'
and period between '201801' and '202102'
and account ='1300'
group by dim_6
),
t1 AS (
select dim_6, sum(amount) as amount
from agltransact
where dim_6= 'AWD-000261'
and voucher_type!='YE'
and period between '201801' and '202102'
and account ='1301'
group by dim_6
)
select t.dim_6, t.amount as bvalue, t1.amount as b1value
from t
left outer join t1
on t1.dim_6 = t.dim_6
或者,如果您想避免CTE
,您可以使用如下所示的子查詢。 將t1 cte as a sub query
,並將left join with t
使用。 使用t.dim_6, t1.amount
的group by
by
select t.dim_6, sum(t.amount) as bvalue, t1.amount as b1value
from agltransact t
left outer join (
select dim_6, sum(amount) as amount
from agltransact
where dim_6= 'AWD-000261'
and voucher_type!='YE'
and period between '201801' and '202102'
and account ='1301'
group by dim_6
) t1
on t1.dim_6 = t.dim_6
where t.dim_6= 'AWD-000261'
and t.voucher_type!='YE'
and t.period between '201801' and '202102'
and t.account ='1300'
group by t.dim_6, t1.amount
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.