表数据计数最大值

时间:2014-07-21 12:53:43

标签: mysql sql

我在MySQL中有两个表

+---------+-----------+
| machine | status    |
+---------+-----------+
| 40001   | Completed | 
| 40001   | Completed | 
| 40001   | Completed | 
| 40001   | Completed | 
| 40001   | Pending   | 
| 40001   | Pending   | 
| 40001   | Pending   | 
| 40001   | Pending   | 
| 40001   | Pending   | 
| 40001   | Pending   | 
+---------+-----------+
And the other one as
+---------+---------+
| machine | packets | 
+---------+---------+
| 40001   |   527   |
| 40001   |   1497  |
| 40002   |   1414  | 
| 40002   |   2796  |
| 40003   |  392    | 
| 40003   |  1663   | 
| 40004   |   500   | 
| 40004   |   1277  |
+-------+----------+

我想写一个select查询,它给出了该机器的机器,完成计数,挂起计数和最大数据包。所以我试过

SELECT machine,max(packets) AS sync,
      sum(if(laststatus='completed', 1, 0)) AS generation,
      sum(if(laststatus != 'completed', 1, 0)) AS pending
FROM machine_status
right join machine_packets on machine_packets.machine=machine_status.machine
GROUP BY machine

但我得到了:

+---------+------+------------+---------+
| machine | sync | generation | pending |
+---------+------+------------+---------+
| 40001   | 1497 |          8 |       2 | 
| 40002   | 2796 |          4 |       2 | 
| 40003   | 1663 |          6 |       0 | 
| 40004   | 1277 |          0 |       2 | 
| 40005   | 2755 |          0 |       0 | 
| 40006   |  927 |          0 |       0 | 
| 40007   |  306 |          0 |       0 | 
+---------+------+------------+---------+

正如我们所看到的,生成和待定列中的值加倍。我哪里出错了?

2 个答案:

答案 0 :(得分:0)

SELECT machine,sync,
      sum(if(laststatus='completed', 1, 0)) AS generation,
      sum(if(laststatus != 'completed', 1, 0)) AS pending
FROM machine_status
right join (select machine, 
                   max(packets) AS sync 
            from machine_packets 
            group by machine) mp on mp.machine=machine_status.machine
GROUP BY machine

它们加倍,因为machine_packets每个id有2条记录。为避免这种情况,您可以在子查询中移动它

答案 1 :(得分:0)

安全的方法是使用union all

select machine, sum(status = 'completed') then generation,
       sum(status <> 'completed') then pending,
       max(packets) as packets
from ((select machine, status, 0 as packets
       from machine_status
      ) union all
      (select machine, 0, packets
       from machine_packets
      )
     ) m
group by machine;

这将包括任一表中所有计算机的行。