4

我知道我很接近,它正在杀死我。这里需要一双新鲜的眼睛......

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)
  • 克劳迪娅 (19)
  • 珍妮特 (29)
  • 丰富 (21)
  • 汤姆 (4)
  • 未分配 (24)

但是,我非常希望在结果中出现一些零值的结果,如下所示:

  • 阿诺德 (5)
  • 谢丽尔 (0)
  • 克劳迪娅 (19)
  • 辛迪 (0)
  • 珍妮特 (29)
  • 菲尔 (0)
  • 丰富 (21)
  • 汤姆 (4)
  • 未分配 (24)

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

-马特

4

3 回答 3

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
        )
于 2012-05-30T09:01:52.527 回答
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;
于 2012-05-30T08:56:44.180 回答
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
于 2012-05-30T08:49:55.587 回答