MySQL - GROUP BY的多个条件及其结果

时间:2014-01-16 10:38:00

标签: mysql conditional-statements

table name : users u
id   username   src
 1   mark       101
 2   stanley    102
 3   john       103
 4   stewe      104


table name : call_history c
id   src        dst        duration
 1   101        555-1217   20    
 2   555-1315   102        30
 3   555-2245   102        40
 4   102        555-6523   30
 5   102        555-4213   20
 6   555-1689   102        15
 7   103        555-1775   35

有两个表和这些列。 条件是;

SUM(duration)   AS OutboundSUM (Condition: u.src=c.src )
COUNT(duration) AS OutboundCNT (Condition: u.src=c.src )

SUM(duration)   AS InboundSUM  (Condition: u.src=c.dst )
COUNT(duration) AS InboundCNT  (Condition: u.src=c.dst )

我需要使用按用户名分组的内容;

username   OutboundSUM OutboundCNT  InboundSUM  InboundCNT
mark       20          1            0           0
stanley    50          2            85          3
john       35          1            0           0
stewe       0          0            0           0

我尝试了UNION ALL,选择之后的子查询,INNER JOIN但它没有用。 Union为每个用户名提供2行,join让我发疯,子查询需要长时间和错误的结果。

感谢所有帮助。

问题,用Kicstart的解决方案解决了。非常感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您能提供表格的主键吗?这将有助于我们提供更好的答案。 此外,您必须包括u.src = c.src和u.id = c.id这两个条件才能加入。 如果两个表的ID彼此不相关,我建议您使用不同的属性名称。

答案 1 :(得分:0)

几个子查询?

SELECT a.src,
        oBSum AS OutboundSUM,
        oBCnt AS OutboundCNT,
        iBSum AS InboundSUM,
        iBCnt AS InboundCNT
FROM users u
LEFT OUTER JOIN (SELECT src, SUM(duration) AS oBSum, COUNT(*) AS oBCnt FROM call_history GROUP BY src) ob
ON u.src = ob.src
LEFT OUTER JOIN (SELECT dst, SUM(duration) AS iBSum, COUNT(*) AS iBCnt FROM call_history GROUP BY dst) ib
ON u.src = ib.dst