按内容加入内部加入组的总和

时间:2014-02-22 17:13:16

标签: sql sql-server sql-server-2008 sql-server-2008-r2 left-join

我有两个表,MasterChild.我需要Cash表中的Master列的总和,我也指的是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。

2 个答案:

答案 0 :(得分:0)

问题似乎是您的子表两次计算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

答案 1 :(得分:0)

也许这就是你要找的东西:

SELECT BillDate, SUM(Cash) FROM MasterDetails GROUP BY BillDate

如果不是,请准确说明您的预期输出。