[英]Sum With Inner Join Group by Clause
我有兩個桌子, Master
和Child.
我需要“ Master
表中“ Cash
”列的總和,並且我要引用“ Child
表以匹配某些條件。
Master
表:
ID CASH BillDate
1 100 22-02-2014
2 200 22-02-2014
Child
表:
ChildID MasterID
1 1
2 1
3 2
我的查詢:
select CONVERT(varchar,BillDate,103) as BillDate,SUM(cash)as ByCash
from childdetails CD
inner join MasterDetails MD on MD.ID=CD.MasterID
where CONVERT(varchar,BillDate,103)='22/02/2014'
group by BillDate
我的錯誤輸出:
BillDate ByCash
22/02/2014 400
在ByCash
,正確的輸出應為300,但我不確定為什么將其計算為400。
問題似乎是您的子表對MasterID進行了兩次計數。 嘗試選擇子表作為具有row_number的CTE,並按MasterID分區以過濾出重復項:
select
CONVERT(varchar,BillDate,103) as BillDate,
SUM(cash)as ByCash
from (
select *,
row_number() over(partition by MasterID order by ChildID) dedupe
from childdetails
) CD inner join MasterDetails MD on MD.ID=CD.MasterID
where
CONVERT(varchar,BillDate,103)='22/02/2014'
and CD.dedupe = 1
group by BillDate
也許這就是您想要的:
SELECT BillDate, SUM(Cash) FROM MasterDetails GROUP BY BillDate
如果不是,請明確說明您的預期輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.