MySQL:从JOINing Tables中选择最近响应最多日期

时间:2015-11-30 21:08:12

标签: mysql date group-by max

我有一个调查表,只要该人对某项调查作出回应,就会编制非独特的记录,因此他们可以在那里多次 - 我正在试图弄清楚如何将该行调回去最多最近的约会。

这是person表:

ID  First   Last     Employer
1   Jerry   Seinfeld NBC
2   Elaine  Benes    Pendant Publishing
3   George  Costanza Kruger Industrial Smoothing
4   Cosmo   Kramer   Kramerica Industries

这是survey表:

ID  Survey  Response Date
1   9       Yes      4/14/15
1   9       No       8/9/15
2   9       No       10/13/15
3   9       No       6/19/15
3   9       Yes      2/3/15
3   8       IQ       7/27/15
4   9       Yes      5/12/15

如果ID重复且调查编号为9,我只想返回最近日期的行。

以下是我一直在尝试的内容:

SELECT p.id, p.first, p.last, p.employer, s.response, s.date
FROM person p
LEFT JOIN
    (SELECT s1.id, s1.survey, s1.response, s1.date, MAX(s1.date)
     FROM survey s1
     WHERE s1.survey = 9
     GROUP BY s1.id) AS s ON s.id = p.id
ORDER BY s.date;

但是每当我这样做时,行的最大日期和实际日期有时都不匹配 - 所以MAX函数正常工作但只是关于ID,而不是关于给我那一排。但是我必须对ID进行分组才能正确匹配这两个表,这就是我遇到的问题。

当我尝试这样的事情时,我收到Invalid use of group function错误:

SELECT p.id, p.first, p.last, p.employer, s.response, s.date
FROM person p
LEFT JOIN
    (SELECT s1.id, s1.survey, s1.response, s1.date, MAX(s1.date)
     FROM survey s1
     WHERE s1.survey = 9 AND MAX(s1.date) = s1.date
     GROUP BY s1.id) AS s ON s.id = p.id
ORDER BY s.date;

我想要的结果如下:

ID  First   Last     Employer                    Response   Date
3   George  Costanza Kruger Industrial Smoothing Yes        2/3/15
4   Cosmo   Kramer   Kramerica Industries        Yes        5/12/15
1   Jerry   Seinfeld NBC                         No         8/9/15
2   Elaine  Benes    Pendant Publishing          No         10/13/15

1 个答案:

答案 0 :(得分:0)

这是经过测试的查询:

select `person`.*,`survey`.`Response`,`survey`.`Date`
from `survey`
inner join 
    (
      SELECT ID,max(`Date`) as `d`
      FROM `survey` 
      WHERE `Survey`=9
      group by ID
    ) as `t` on `t`.`ID` = `survey`.`ID` and 
      `t`.`d` = `survey`.`Date`
inner join `person` on `person`.`ID` = `survey`.`ID`