Select 按列分组的最大值
Select max value for group by column
我有一个 table Question
列
QuestionId, Question, AnswerId, Answer, AnsVotes(integer), AnsDate(Date)
一个 QuestionId
可以有多个 AnswerId
,因此有多个条目。 AnswerId
是独一无二的
我如何过滤记录以获得 QuestionId
的记录,其中 AnswerId
的最大值为 AnsVotes
?如果 Ansvotes
对于多个条目相同,则获取最新 AnsDate
的行(这是一个日期列)。
您想获得没有 allwing 的顶级参赛作品。为此使用 TOP(1)
:
select top(1) *
from question
order by ansvotes desc, ansdate desc;
或者您希望每个问题获得最佳答案?然后你会用 ROW_NUMBER
:
对你的记录进行排名
select *
from
(
select q.*, row_number() over (partition by questionid
order by ansvotes desc, ansdate desc) as rn
from question q
) answers
where rn = 1;
我有一个 table Question
列
QuestionId, Question, AnswerId, Answer, AnsVotes(integer), AnsDate(Date)
一个 QuestionId
可以有多个 AnswerId
,因此有多个条目。 AnswerId
是独一无二的
我如何过滤记录以获得 QuestionId
的记录,其中 AnswerId
的最大值为 AnsVotes
?如果 Ansvotes
对于多个条目相同,则获取最新 AnsDate
的行(这是一个日期列)。
您想获得没有 allwing 的顶级参赛作品。为此使用 TOP(1)
:
select top(1) *
from question
order by ansvotes desc, ansdate desc;
或者您希望每个问题获得最佳答案?然后你会用 ROW_NUMBER
:
select *
from
(
select q.*, row_number() over (partition by questionid
order by ansvotes desc, ansdate desc) as rn
from question q
) answers
where rn = 1;