如何在查询中计算联合的总和

时间:2018-05-13 19:15:36

标签: sql ms-access-2010

这就是我所做的,在图像中结果现在我想通过UserSend得到所有组的总和,例如 你可以看到maorsapo@gmail.com 在第二个中有7个和3个 我想要的不是这个 它将是maorsapo@gmail.com,10(7 + 3) 我怎么能这样做?

SELECT m.UserSend, Count(*) AS Expr1
FROM Messages AS m
GROUP BY m.UserSend;
union
SELECT F.UserRequest, Count(*) AS Expr1
FROM FavoritesList AS F
GROUP BY F.UserRequest;

https://ibb.co/cbuKrJ

3 个答案:

答案 0 :(得分:1)

您可以尝试使用结果表的总和

select t.my_user, sum(Expr1)
from (
    SELECT m.UserSend as  my_user, Count(*) AS Expr1
    FROM Messages AS m
    GROUP BY m.UserSend;
    union
    SELECT F.UserRequest, Count(*) AS Expr1
    FROM FavoritesList AS F
    GROUP BY F.UserRequest;
) t 
group by t.my_user

答案 1 :(得分:0)

您需要union all而不是union

SELECT user, sum(cnt)
FROM (SELECT m.UserSend as user, Count(*) AS cnt
      FROM Messages AS m
      GROUP BY m.UserSend;
      UNION ALL
      SELECT F.UserRequest, Count(*) AS cnt
      FROM FavoritesList AS F
      GROUP BY F.UserRequest
     ) as u
GROUP BY user;

UNION将删除重复项,您不想这样做。

我记得MS Access的某些旧版本需要一个视图才能完成此操作,因为子查询中不允许使用union / union all。但这应该没问题。

答案 2 :(得分:0)

非常感谢你 SELECT用户,总和(cnt) FROM(选择m.UserSend作为用户,Count()AS cnt       来自消息AS m       GROUP BY m.UserSend;       UNION ALL       SELECT F.UserRequest,Count()AS cnt       FROM FavoritesList AS F.       GROUP BY F.UserRequest      )作为你 GROUP BY用户;