通过mysql统计总数,活动数和非活动数

时间:2017-09-25 17:18:17

标签: mysql sql

我的代码示例获取总total_stamp,我需要有效和无效。我的邮票表有活动和非活动的current_status行

SELECT r.*
     , COUNT(s.current_status) total_stamp
  FROM tbl_registers r
  LEFT 
  JOIN tbl_stamps s
    ON r.register_id = s.register_id
 WHERE r.ins_id = 1
 GROUP 
    BY r.register_id
 ORDER BY r.register_name_en ASC
     , s.stamp_name_en ASC

enter image description here

当前这样的输出,我需要另一个更多的第一行是total_active另一个是完全不活动的单个查询。

2 个答案:

答案 0 :(得分:2)

SELECT r.*, 
       COUNT(s.current_status), 
       SUM(current_status='something meaning active') active,
       SUM(current_status='something meaning inactive') inactive,
       ...

应该做的伎俩。为什么?因为MySQL中的current_status='something meaning inactive'等表达式的值为0表示为false,或者1表示为true。所以SUM()会增加真实项目的数量。

答案 1 :(得分:0)

我认为实现这一目标的最佳方法是将LEFT JOIN分成两个单独的LEFT JOINS。一个到活动的表和另一个不活动的表。通过这种方式,您可以分别对三者求和。那有意义吗?像这样:

SELECT r.*, sActive.total + sInactive.total as total_stamp, sActive.total as active_stamp, sInactive.total as inactive_stamp
FROM tbl_registers as r
LEFT JOIN (
    SELECT register_id, COUNT(*) as total
    FROM tbl_stamps
    WHERE s.current_status = 'active'
    GROUP BY register_id
) as sActive ON sActive.register_id = r.register_id
LEFT JOIN (
    SELECT register_id, COUNT(*) as total
    FROM tbl_stamps
    WHERE s.current_status = 'inactive'
    GROUP BY register_id
) as sInactive ON sInactive.register_id = r.register_id
GROUP BY r.register_id