简体   繁体   English

每个人有两个ID的总行数

[英]Sum rows per person with two IDs

I have two tables, one with people and one with values. 我有两张桌子,一张桌子与人,一张桌子与价值观。 Each person can have two IDs and I need the values assigned to their IDs in the second table to sum with each other (so all of ID1's values would be a single value that is also combined with ID2's values). 每个人可以有两个ID,我需要在第二张表中分配给他们的ID的值相互求和(因此ID1的所有值都是一个值,也与ID2的值组合在一起)。

Table a
ID  ID2 FName
1   4   Jacob
56  13  John

Table b
ID  AID V1  V2
1   4   50  25
2   13  30  0
3   1   10  15
4   4   0   5

Goal output
SUM(V1,V2)  a.ID    a.ID2   FName
105         1       4       Jacob
30          56      13      John

I was able to get the value from one ID with 我能够从一个ID获取值

SELECT SUM(V1,V2) AS Total, AID, FName
FROM a,b
WHERE b.AID=a.ID
GROUP BY AID
ORDER BY Total DESC

I'm guessing I need a subquery to do both at once, but I wasn't sure how to work it in. 我猜想我需要一次子查询才能同时执行这两个操作,但是我不确定如何使用它。

select
    sum(b.V1 + b.V2) as Total,
    a.ID,
    a.ID2,
    a.FName
from
    a
    inner join b on
        a.ID = b.AID
        or a.ID2 = b.AID
group by
    a.ID,
    a.ID2,
    a.FName;

Does this work? 这样行吗? I don't have a way to test it right now. 我目前没有办法对其进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM