1

我在表中有以下行:

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

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

编辑 - 请记住,这是一个带有许多 JOINS 的 VERY LARGE 查询的精简版本......做 TOP 和 ORDER BY 是不够的。我需要一个 GREATEST(date) 函数之类的东西。

4

5 回答 5

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 */
于 2013-06-18T01:31:12.717 回答
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
于 2013-06-18T01:45:38.630 回答
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
于 2013-06-18T01:28:46.423 回答
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 
于 2013-06-18T01:28:53.223 回答
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
于 2013-06-18T01:37:40.793 回答