mysql查询获取与其公司快递相关的每个状态的计数

时间:2014-04-22 08:45:19

标签: mysql sql

我有两张桌子

  1. company_details ---- company_id, name, address
  2. company_courier_status ---- courier_id, company_id, status
  3. 状态列将包含0,1,2值

    0 --- processing
    1 --- success
    2 --- returned 
    

    如何编写mysql查询以获取以下输出

    company_name  processing  success returned
    

    处理列值是具有0的状态列值的计数 类似的成功和返回列

    提前致谢

1 个答案:

答案 0 :(得分:0)

你可以这样做:

SELECT
  a.name AS company_name,
  SUM(b.status = 0) AS processing,
  SUM(b.status = 1) AS success,
  SUM(b.status = 2) AS returned
FROM company_details a
LEFT JOIN company_courier_status b ON a.company_id = b.company_id
GROUP BY a.company_id, a.name