如何根据每个参数仅选择一个条目

时间:2015-05-20 15:04:44

标签: sql sql-server database

之前可能已经提出过这个问题,但我一开始并不知道如何找到它。

在以下查询中(具有相应的返回值):

select * from tbChapter where idLesson in(12, 13)

- 结果 -

id    idLesson    name              sequence
52    12          Intro             1
53    12          Chapter One       2
54    12          Chapter Two       3
55    13          Intro             1
56    13          Chapter One       2
57    13          Chapter Two       3
58    13          Chapter Three     4

我想只获取每个idLesson的最后一个条目,例如:

- 预期结果 -

id    idLesson    name              sequence
54    12          Chapter Two       3
58    13          Chapter Three     4

我该怎么办?

Ps:我实际上将where idLesson in(12, 13)替换为将返回数十个idLesson值的子查询。

4 个答案:

答案 0 :(得分:2)

试试这个:

select * 
from tbChapter as a
where sequence = (select max(sequence)
                  from tbChapter as b
                  where a.id_lesson = b.id_lesson)

答案 1 :(得分:2)

规范的方法是使用窗口函数。这是一个例子:

select c.*
from (select c.*, max(sequence) over (partition by idLesson) as maxs
      from tblChapter c
     ) c
where sequence = maxs;

在某些情况下可能表现更好的更有创意的方法是使用cross apply

select c.*
from (select distinct idLesson from tblChapter) l cross apply
     (select top 1 c*
      from tblChapter c
      where c.idLesson = l.idLesson
      order by sequence desc
     ) c;

请注意,第一个子查询可以替换为包含所有课程的表,每行一个。

答案 2 :(得分:2)

试试这个:

  select * from tbChapter  where id in
  (select MAX(id) from tbChapter group by idLesson)

答案 3 :(得分:2)

SELECT
   Max(id),
   idlesson,
   name,
   Max(sequence)
FROM
   tbChapter
WHERE
   idLesson in(12, 13)
GROUP BY
   idlesson,
   name