-1

我有一个修改日期和创建日期的表。修改日期可以为空,但创建日期不能为空。还有另一列是非唯一的学号。

现在,我想从表格中找到具有特定学号的最新记录。

我正在使用以下查询:

Select Top (1) * from student_data order by modified_date desc, created_date desc

但它不起作用,因为修改日期可以为空。

Student Nr    Modified_date             Created_date
12345         NULL                  2013-09-02 11:41:30.967
12345         2013-09-02 11:42:20.663   2013-09-02 11:38:20.663
12345         2013-09-02 11:39:46.103   2013-09-02 11:38:10.660
12345         2013-09-02 11:37:59.480   2013-09-02 11:37:59.480
12345         NULL                  2013-09-02 11:37:44.477

它应该返回我以下记录:

12345         2013-09-02 11:42:20.663   2013-09-02 11:38:20.663
4

3 回答 3

1
SELECT TOP (1) *
FROM
  ( SELECT TOP (1) *
    FROM student_data 
    ORDER BY modified_date DESC
  UNION ALL
    SELECT TOP (1) *
    FROM student_data 
    ORDER BY created_date DESC
  ) t 
ORDER BY 
  CASE WHEN modified_date > created_date 
           THEN modified_date
           ELSE created_date
  END DESC ;

SQL-Fiddle测试

于 2013-09-02T07:27:43.880 回答
0

我认为这个 sql 请求会对您有所帮助,其中 :student_id 是特定的学生编号。

SELECT TOP 1 * FROM
 (Select * from student_data AS sd
  WHERE sd.modified_date IS NOT NULL
        AND sd.student_id = :student_id) as TMP
 ORDER BY modified_date desc, created_date desc
于 2013-09-02T07:11:00.630 回答
0

请尝试以下查询

Select Top (1) * from student_data order by coalesce(modified_date, created_date) desc
于 2013-09-02T07:50:08.240 回答