MySQL计数行包括零(非常接近我想要的!)

时间:2012-05-30 08:42:03

标签: mysql join count

我知道我很亲密,它正在杀了我。这里需要一双新鲜的眼睛......

SELECT 
first_name, 
COUNT(*) FROM 
(SELECT first_name, job_status FROM typesetting 
LEFT JOIN employees ON typesetting.employees_id = employees.id 
LEFT JOIN job_status ON typesetting.job_status_id = job_status.id 
WHERE job_status NOT LIKE 'Archived' 
ORDER BY first_name ASC) 
AS CNT 
GROUP BY first_name

这让我:

  • 阿诺德(5)
  • Claudia(19)
  • 珍妮特(29)
  • Rich(21)
  • 汤姆(4)
  • 未分配(24)

然而,在结果中有一些我想要的值为零的结果,如下所示:

  • 阿诺德(5)
  • Cheryl(0)
  • Claudia(19)
  • Cyndi(0)
  • 珍妮特(29)
  • Phil(0)
  • Rich(21)
  • 汤姆(4)
  • 未分配(24)

我做错了什么?很近!谢谢!

-Matt

3 个答案:

答案 0 :(得分:1)

在INNER查询中,您会过滤掉所有可能会为您提供0结果的人。

试试这个:

SELECT first_name,
       sum(CASE WHEN job_status = 'Archived' THEN 1 ELSE 0 END) AS cnt
  FROM typesetting 
  LEFT JOIN employees ON typesetting.employees_id = employees.id 
  LEFT JOIN job_status ON typesetting.job_status_id = job_status.id 
GROUP BY first_name
ORDER BY first_name ASC;

答案 1 :(得分:1)

SELECT  first_name, COUNT(js.id)
FROM    employees e
LEFT JOIN
        typesetting ts
ON      ts.employees_id = e.id
LEFT JOIN
        job_status js
ON      js.id = ts.job_status_id
        AND js.status <> 'Archived'
GROUP BY
        first_name
UNION ALL
SELECT  'Unassigned', COUNT(*)
FROM    typesetting ts
JOIN    job_status js
ON      js.id = ts.job_status_id
        AND js.status <> 'Archived'
WHERE   ts.employees_id NOT IN
        (
        SELECT  id
        FROM    employees
        )

答案 2 :(得分:0)

如果我的查询正确。你可以这样做:

SELECT
    employees.first_name,
    (
        SELECT
            COUNT(*)
        FROM
            typesetting
            JOIN job_status ON typesetting.job_status_id = job_status.id 
        WHERE
            typesetting.employees_id = employees.id
            AND job_status NOT LIKE 'Archived' 
    )
FROM
    employees
ORDER BY 
    first_name ASC