查询两个表的总和值

时间:2014-02-23 01:04:37

标签: sql-server-2008

我面临的问题是sum_value:enter image description here

假设我在家庭中向payment_value支付200美元给父亲和母亲支付300美元儿童支付给每个孩子100美元..现在我想查询这个以计算此家庭的payment_value ..我希望它像这样 table result

我想要这样的SQL查询:

SELECT 
    family_id,
    father_name,
    mother_name,
    last_name,
    'children count' AS [here count children for each family],
    'sumpayment' AS [here i want sum payment for father and mother and children]
FROM dbo.Families

2 个答案:

答案 0 :(得分:1)

select
    f.family_id,
    f.father_name,
    f.mother_name,
    f.last_name,
    cp.children_count,
    isnull(cp.children_payment,0) + isnull(fp.families_payment,0) sumpayment
FROM dbo.Families f
    inner join  (
                select
                    c.family_id,
                    count(distinct c.child_id) children_count,
                    sum(p.payment_value) children_payment
                from dbo.Children c
                    inner join ChildrenPayments p
                        on p.child_id = c.child_id
                group by
                    c.family_id
                ) cp
        on cp.family_id = f.family_id
    inner join  (
                select
                    p.family_id,
                    sum(p.payment_value) families_payment
                from familiesPayments p
                group by
                    p.family_id
                ) fp
        on fp.family_id = f.family_id

SLQ小提琴链接:http://www.sqlfiddle.com/#!2/d7e43/13

答案 1 :(得分:0)

试试这个

SELECT 
f.family_id, f.father_name, f.mother_name, f.last_name, count(c.childId) AS TotalChildren
, sum(fp.paymentValue + cp.paymentValue)
FROM dbo.Families f inner join familiesPayment fp on f.family_id = fp.family_id inner join children c on f.family_id = c.family_id inner join childrenPayment cp on c.child_id = cp.child_id
group by  f.family_id, f.father_name, f.mother_name, f.last_name