如何使用嵌套查询从连接表中添加其他字段?

时间:2014-10-06 16:30:10

标签: mysql sql nested-queries

我有以下代码可以完美地计算过去一年中完成一个以上志愿者班次的志愿者(不是员工)的数量:

SELECT count(*) AS Volunteers
    FROM (
          SELECT COUNT(CASE WHEN (STR_TO_DATE(t2.date,'%m/%d/%Y') > SUBDATE(now(), INTERVAL 1 year)) AND t2.status="Completed" AND t1.sector<>"Staff" THEN t2.id END) AS count
          FROM t2
          LEFT JOIN t1 ON t1.id = t2.id
          GROUP BY t2.id
          HAVING (count > 1)
         ) AS Volunteers;

但是我无法弄清楚如何将其分解,而不仅仅是给出我的总计数。我想看看谁招募了这些人,例如 - 但我无法弄清楚如何将其添加到此代码中。这显然不起作用:

SELECT t2.recruitedby, count(*) AS Volunteers
    FROM (
          SELECT COUNT(CASE WHEN (STR_TO_DATE(t2.date,'%m/%d/%Y') > SUBDATE(now(), INTERVAL 1 year)) AND t2.status="Completed" AND t1.sector<>"Staff" THEN t2.id END) AS count
          FROM t2
          LEFT JOIN t1 ON t1.id = t2.id
          GROUP BY t2.id
          HAVING (count > 1)
         ) AS Volunteers;

因为很明显你会得到错误Unknown column 't2.recruitedby' in 'field list',因为我没有指定列的来源 - 但如果我尝试在底部添加“FROM t2”,我会收到“错误” SQL语法“消息。我知道我可能不得不再次使用GROUP BY - 但我还没有那么远。

最后,理想情况下,我想在此查询中添加更多列,以便将志愿者从t1中分解出来 - 所以,如果LEFT JOIN也能以某种方式包含在内,那么这就是很棒 - 但是我想在没有加入任何东西的情况下提出这个问题,这样我至少可以迈出第一步。

谢谢!

1 个答案:

答案 0 :(得分:2)

你需要子查询吗? (由于名称重复的可能性,由2列分组)

SELECT t2.id, t2.recruitedby, COUNT(1) AS count
FROM t2
LEFT JOIN t1 ON t1.id = t2.id
WHERE
    STR_TO_DATE(t2.date,'%m/%d/%Y') > SUBDATE(now(), INTERVAL 1 year
    AND t2.status="Completed"
    AND t1.sector<>"Staff"
GROUP BY t2.id, t2.recruitedby
HAVING (count > 1)

编辑:上面的命令返回不需要的结果。如果您的问题中的查询为志愿者返回了正确的结果,那么该命令如何做?

SELECT t2.recruitedby, COUNT(Volunteers.count) AS Volunteers
FROM (
    SELECT t2.id, COUNT(CASE 
        WHEN (STR_TO_DATE(t2.date,'%m/%d/%Y') > SUBDATE(now(), INTERVAL 1 year))
        AND t2.status="Completed"
        AND t1.sector<>"Staff"
        THEN t2.id END) AS count
    FROM t2
    LEFT JOIN t1 ON t1.id = t2.id
    GROUP BY t2.id
    HAVING (count > 1)
   ) AS Volunteers
JOIN t2 ON t2.id=Volunteers.id

编辑:以下查询(不漂亮)返回以下行:

Smith, Jane    2
Smith, John    1

以下是查询:

SELECT recruiters.recruitedby, COUNT(Volunteers.id) AS Volunteers
FROM
(
    SELECT t2.id, COUNT(CASE 
        WHEN (STR_TO_DATE(t2.date,'%m/%d/%Y') > SUBDATE(now(), INTERVAL 1 year))
        AND t2.status="Completed"
        AND t1.sector<>"Staff"
        THEN t2.id END) AS count
    FROM t2
    LEFT JOIN t1 ON t1.id = t2.id
    GROUP BY t2.id
    HAVING (count > 1)
) AS Volunteers
JOIN
(
    SELECT DISTINCT id, recruitedby
    FROM t2
) AS recruiters
ON recruiters.id=Volunteers.id
GROUP BY recruiters.recruitedby

我认为我从未写过像这样的查询!