简体   繁体   English

SQL请求最大分组

[英]sql request Max Group by

Hi guys Could you help me. 大家好,您能帮我吗。 Please find below images with input and output data So I need to code sql request to show only the maximum date in each competence_question_id, and also show a value of competence_answer_id with this date (I also have grouping by response_id but i hide it here) 请在下面的图片中输入和输出数据,所以我需要对sql request进行编码,以仅显示每个capetent_question_id中的最大日期,并且还显示该日期中的compence_answer_id的值(我也可以通过response_id进行分组,但我将其隐藏在此处)

Thank you in advance 先感谢您

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 表二带有输出数据

Try the following query for the desired result. 请尝试以下查询以获得所需的结果。

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

If the date_created column doesn't have the date repeated, then you can use a derived table (where the max(date_created) is obtained for the competence_question_id) joined back to the original table: 如果date_created列中没有重复的日期,则可以使用派生表(在该表中,对于compencence_question_id获得了max(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM