MAX()函数无法正常工作

时间:2014-01-07 11:32:04

标签: mysql sql select group-by max

我已经创建了sqlfiddle,试图了解这个http://sqlfiddle.com/#!2/21e72/1

在查询中,我在compiled_date列上放了一个max()但是推荐列仍然不正确 - 我假设某个select语句需要以某种方式插入第3行?

我已经尝试过以下评论者提供的示例,但我认为我只需要从基本查询开始理解这一点。

4 个答案:

答案 0 :(得分:5)

正如其他人所指出的那样,问题是某些select列既未聚合也未在group by子句中使用。大多数DBMS根本不允许这样做,但MySQL在某些标准上有点放松......

因此,您需要先为每个案例找到max(compiled_date),然后找到与之相关的建议。

select r.case_number, r.compiled_date, r.recommendation
from reporting r
  join (
    SELECT case_number, max(compiled_date) as lastDate
    from reporting
    group by case_number
  ) s on r.case_number=s.case_number
      and r.compiled_date=s.lastDate

答案 1 :(得分:3)

感谢您提供sqlFiddle。但只提供报告数据。如果您向我们提供整个表格的样本数据,我们非常感谢。

无论如何,你能试试吗?

SELECT
    `case`.number,
    staff.staff_name AS ``case` owner`,
    client.client_name,
    `case`.address,
    x.mx_date,
    report.recommendation
FROM
    `case` INNER JOIN (
        SELECT case_number, MAX(compiled_date) as mx_date
        FROM report
        GROUP BY case_number
    ) x ON x.case_number = `case`.number
    INNER JOIN report ON x.case_number = report.case_number AND report.compiled_date = x.mx_date
    INNER JOIN client ON `case`.client_number = client.client_number
    INNER JOIN staff ON `case`.staff_number = staff.staff_number
WHERE
    `case`.active = 1
    AND staff.staff_name = 'bob'
ORDER BY
    `case`.number ASC;

答案 2 :(得分:0)

检查以下查询:

SELECT c.number, s.staff_name AS `case owner`, cl.client_name, 
       c.address, MAX(r.compiled_date), r.recommendation
FROM case c
INNER JOIN (SELECT r.case_number, r.compiled_date, r.recommendation 
            FROM report r ORDER BY r.case_number, r.compiled_date DESC
           ) r ON r.case_number = c.number
INNER JOIN client cl ON c.client_number = cl.client_number
INNER JOIN staff s ON c.staff_number = s.staff_number
WHERE c.active = 1 AND s.staff_name = 'bob'
GROUP BY c.number
ORDER BY c.number ASC

答案 3 :(得分:-1)

SELECT
case.number,
staff.staff_name AS `case owner`,
client.client_name,
case.address,
(select MAX(compiled_date)from report where case_number=case.number),
report.recommendation
FROM
case
INNER JOIN report ON report.case_number = case.number
INNER JOIN client ON case.client_number = client.client_number
INNER JOIN staff ON case.staff_number = staff.staff_number
WHERE
case.active = 1 AND
staff.staff_name = 'bob'
GROUP BY
case.number
ORDER BY
case.number ASC

试试这个