SQL使用聚合查询获取正确的数据集

时间:2017-07-06 05:03:40

标签: sql

user table

calls table

sms

所以我有用户,电话,短信表,现在我想得到每个用户的传入和传出呼叫和短信的数量

我有这个查询

select u.username,
        sum(case when c.type = 'incoming' then 1 else 0 end) as  incoming,
        sum(case when c.type = 'incoming' and status = 'true' then 1 else 0 end) as  answered,
        sum(case when c.type = 'outgoing' then 1 else 0 end) as  outgoing,
        sum(case when s.type = 'in'   then 1 else 0 end )  as sms
 from user u  
 join
      calls c
      on u.id = c.user_id
 join 
      sms s
      on u.id = s.user_id

 group by u.username;

结果就是这个

enter image description here

调用中的传入和传出是正确的但是在短信中,用户样本中的结果是错误的,它应该是列sms中的1而不是4

1 个答案:

答案 0 :(得分:1)

为了避免您对连接产生的乘法效应,您可以尝试按用户单独聚合调用和短信表,然后加入这些子查询:

SELECT
    u.username,
    COALESCE(t1.incoming, 0) AS incoming,
    COALESCE(t1.answered, 0) AS answered,
    COALESCE(t1.outgoing, 0) AS outgoing,
    COALESCE(t2.sms, 0) AS sms
FROM user u
LEFT JOIN
(
    SELECT
        user_id,
        SUM(CASE WHEN type = 'incoming' THEN 1 ELSE 0 END) AS  incoming,
        SUM(CASE WHEN c.type = 'incoming' AND status = 'true'
                 THEN 1 ELSE 0 END) AS answered,
        SUM(CASE WHEN c.type = 'outgoing' THEN 1 ELSE 0 END) AS outgoing
    FROM calls
    GROUP BY user_id
) t1
    ON u.id = t1.user_id
LEFT JOIN
(
    SELECT
        user_id,
        SUM(CASE WHEN s.type = 'in' THEN 1 ELSE 0 END) AS sms
    FROM sms
    GROUP BY user_id
) t2
    ON u.id = t2.user_id
相关问题