合并 SQL 个表以保留最新的行

Merging SQL tables keeping the latest rows

我有一个现有的 SQL table 有点像这样

Question Answer AnsWhen AnsWho
Q1 Red 2022-03-01 Rod
Q1 Green 2022-03-20 Freddie
Q2 Blue 2022-04-05 Jane
Q2 Yellow 2022-04-01 Rod
Q3 Green 2022-04-05 Jane
Q3 Green 2022-04-04 Rod
Q3 Green 2022-04-06 Freddie

我需要删除重复的问题,只保留最新的数据,所以完成的table看起来像

Question Answer AnsWhen AnsWho
Q1 Green 2022-03-20 Freddie
Q2 Blue 2022-04-05 Jane
Q3 Green 2022-04-06 Freddie

如果你的数据库支持,ROW_NUMBER可以在这里使用:

WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY Question ORDER BY AnsWhen DESC) rn
    FROM yourTable t
)

SELECT Question, Answer, AnsWhen, AnsWho
FROM cte
WHERE rn = 1;

我没有测试过,大概是这样。

with cteQuestions
as
(
select a.question,max(a.AnsWhen) as MAX_DATE
from tblAnswers as a
group by a.question
)
select q.question,a.answer,q.MAX_DATE,a.AnsWho
from cteQuestions as q
left join tblAnswers as a on q.question=a.question and q.max_date=a.AnsWhen