SQL仅使用较晚的日期返回行

时间:2013-06-18 01:24:45

标签: sql sql-server sql-server-2008 greatest-n-per-group

我在表格中有以下行:

user_id school_id graduation_date 
------- --------- ---------------
1             123      2006-05-19 
1             123      2008-05-19
2             123      2006-05-19
2             123      2008-05-19

我有以下查询:

SELECT * FROM user_school us, [user] u
WHERE us.user_id = u.user_id
AND us.school_id = 123

我想在最后添加一个子句,只返回一行;具有最新毕业日期的行 - 所以在这种情况下,两行中的第二行。我希望能够获得一排PER学生。所以,每个学生的最新毕业日期。

编辑 - 请记住,这是一个包含许多JOINS的非常大的查询的删节版本...执行TOP和ORDER BY是不够的。我需要一个最棒的(约会)功能或其他东西。

5 个答案:

答案 0 :(得分:3)

鉴于您对TOP和ORDER BY的限制,您无法一举完成这些。

您可以找到最近的毕业日期,然后找到它的行。

SELECT *
FROM (
  SELECT user_id,
         school_id,
         row_number() over (partition by user_id order by graduation_date desc) position
  FROM user_school
) us,
[user] u
WHERE us.user_id = u.user_id
  AND position = 1 /* limits to highest graduation date */

答案 1 :(得分:2)

最简单的方法是使用row_number()

select *
from (SELECT *,
             row_number() over (partition by us.user_id
                                order by graduation_date desc) as seqnum
      FROM user_school us join
           [user] u
           on us.user_id = u.user_id
      where us.school_id = 123
     ) t
where seqnum = 1

答案 2 :(得分:1)

老实说,我不确定我是否理解这个问题,但根据我所得到的,这应该可以解决问题

SELECT TOP 1 * FROM user_school us, [user] u
WHERE us.user_id = u.user_id
AND us.user_id = 1
ORDER BY u.graduation_date DESC

答案 3 :(得分:1)

使用ORDER BYLIMIT

SELECT TOP 1 * FROM user_school us, [user] u 
WHERE us.user_id = u.user_id AND us.user_id = 1 
ORDER BY u.graduation_date DESC 

答案 4 :(得分:0)

你想要的东西是:

SELECT
 field1,
 field2, 
 ...
   (SELECT MAX(graduation_date)
                       FROM user_school
                       WHERE user_id = us.user_id) as max_grad_date
FROM
 student_table_name