簡體   English   中英

與內部加入總和(按條款)

[英]Sum With Inner Join Group by Clause

我有兩個桌子, MasterChild. 我需要“ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM