我面临的问题是sum_value:
假设我在家庭中向payment_value支付200美元给父亲和母亲支付300美元儿童支付给每个孩子100美元..现在我想查询这个以计算此家庭的payment_value ..我希望它像这样
我想要这样的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
答案 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
答案 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