一个查询从不同表中计数

时间:2019-10-10 15:58:23

标签: sql sql-server azure

表用户登录:

userid  logintime
11111   2019.10.10
11111   2019.09.10
22222   2019.10.10

餐桌上的好处:

userid  benefit
11111   A
11111   B
22222   C
22222   C
22222   C

我希望结果为:

userid  benefitcount logincount
11111   2            2
22222   3            1

此代码无效。我怎样才能解决这个问题?

select count(B.userid) as benefitcounts, count(UL.userid) as userlogins
from userlogins UL
inner join benefit B on B.userid=UL.userid
group by UL.userid

谢谢

2 个答案:

答案 0 :(得分:2)

您可以JOIN聚合两个子查询,如下所示:

SELECT 
    u.userid,
    u.logincount,
    b.benefitcount
FROM
(
    SELECT userid, COUNT(*) logincount FROM userlogins GROUP BY userid
) u
INNER JOIN (
    SELECT userid, COUNT(*) benefitcount FROM benefits GROUP BY userid
) b ON u.userid = b.userid

如果每个表中都有一个唯一键,则可以优化此查询:

SELECT 
    u.userid,
    COUNT(DISTINCT u.id) logincount,
    COUNT(DISTINCT b.id) benefitcount
FROM userlogins u
INNER JOIN benefitcount b ON u.userid = b.userid
GROUP BY u.userid

答案 1 :(得分:1)

尽管就性能而言可能不是最佳选择,但这应该会产生所需的输出

SELECT A.userid, B.count as benefitcount, A.count as logincount
FROM
(
    SELECT userid, COUNT(*) AS count
    FROM benefits
    GROUP BY userid
) A
INNER JOIN
(
    SELECT userid, COUNT(*) AS count
    FROM userlogins
    GROUP BY userid
) B
ON A.userid = B.userid;