SQL ORACLE - 在多个表中单独计算COUNT

时间:2016-10-26 08:24:59

标签: sql oracle count

我有桌子:USER,SUBSCRIPTION,FAVORITE和HISTORY。我想计算订阅数量,收藏数量和每个用户的历史数量

SELECT 
    U.idUser,
    COUNT(S.idUser) AS nb_sub,
    COUNT(F.idUser) AS nb_fav,
    COUNT(H.idUser) AS nb_his
FROM
    USER U,
    SUBSCRIPTION S, 
    HISTORY H, 
    FAVORITE F
WHERE
    U.idUser = S.idUser AND
    U.idUser = F.idUser AND
    U.idUser = H.idUser
GROUP BY
    U.idUser;

我试过了,但这不是我想要的结果..

感谢您的帮助

3 个答案:

答案 0 :(得分:4)

试试这个:

SELECT 
    U.idUser,
    (SELECT COUNT(*) FROM SUBSCRIPTION S WHERE U.idUser = S.idUser) AS nb_sub,
    (SELECT COUNT(*) FROM HISTORY H WHERE U.idUser = H.idUser) AS nb_fav,
    (SELECT COUNT(*) FROM FAVORITE F WHERE U.idUser = F.idUser) AS nb_his
FROM USER U

答案 1 :(得分:2)

select U.IDUser, 
       nb_sub,
       nb_fav,
       nb_his
from USER U
left join 
    (
    select idUser, count(*) as nb_sub from Subscription group by idUser
    ) S
  on U.idUser = S.idUser
left join 
    (
    select idUser, count(*) as nb_his from History group by idUser
    ) H
  on U.idUser = H.idUser
left join 
    (
    select idUser, count(*) as nb_fav from Favourite group by idUser
    ) F
  on U.idUser = F.idUser

答案 2 :(得分:2)

P.S。

除了出色的性能之外,当面对缺少诸如" USER"之类的表格时,这种方法具有一个主要优势,因为不需要使用FULL JOIN也不需要生成将起作用的子查询作为LEFT JOIN的基础

解决方案1 ​​

select      *  

from        (           select 'U' as tab ,idUser from "USER"
            union all   select 'S'        ,idUser from Subscription
            union all   select 'F'        ,idUser from Favourite
            union all   select 'H'        ,idUser from History
            )
            pivot (count(*) for tab in ('S' as nb_sub,'F' as nb_fav,'H' as nb_hist))            
;

解决方案2

此解决方案的语法清晰度较低,但您可以自由地操作数据,例如。添加 nb_total

select      idUser

           ,count (decode (tab,'U',1))  as nb_user  -- If the data is good there supposed to be 1 record per user
           ,count (decode (tab,'S',1))  as nb_sub
           ,count (decode (tab,'H',1))  as nb_fav
           ,count (decode (tab,'F',1))  as nb_hist    

           ,count (*)                   as nb_total        

from        (           select 'U' as tab ,idUser from "USER"
            union all   select 'S'        ,idUser from Subscription
            union all   select 'F'        ,idUser from Favourite
            union all   select 'H'        ,idUser from History
            )

group by    idUser
;