sql请求Max Group by

时间:2017-11-27 14:40:48

标签: mysql sql-server

你好,伙计们能帮助我吗? 请在下面找到包含输入和输出数据的图像 所以我需要编写sql请求代码,以便只显示每个capability_question_id中的最大日期,并且还显示带有此日期的一个powers_answer_id值(我也通过response_id进行分组,但我将其隐藏在此处)

提前谢谢

SELECT response_id, competence_question_id, competence_answer_id, MAX(date_created)
FROM competence_vote_history
WHERE response_id = 53178
GROUP BY response_id, competence_question_id, competence_answer_id
ORDER BY response_id, competence_question_id

the table one with input data

the table two with output data

2 个答案:

答案 0 :(得分:0)

尝试以下查询以获得所需的结果。

SELECT competence_question_id, competence_answer_id, date_created, answer_value
FROM competence_vote_history i
WHERE response_id = 53178 
    AND date_created = (
        SELECT MAX(date_created) 
        FROM competence_vote_history 
        WHERE response_id = i.response_id 
        AND competence_question_id = i.competence_question_id)
ORDER BY response_id, competence_question_id

答案 1 :(得分:0)

如果date_created列没有重复日期,那么您可以使用派生表(其中获取compe_question_id的最大值(date_created))连接回原始表:

SELECT V.*
  FROM (
         SELECT competence_question_id, MAX(date_created) AS MAXdate_created
           FROM competence_vote_history
          WHERE response_id = 53178
         GROUP BY competence_question_id
       ) AS dT INNER JOIN competence_vote_history V on dT.competence_question_id = V.competence_question_id
                                                   AND dT.MAXdate_created = V.date_created
ORDER BY response_id, competence_question_id