我有一张表,其中包含修改日期和创建日期。修改日期可以为null,但创建日期永远不能为null。还有另一列学生编号是非独特的。
现在,我想找一张带有特定学号的表格的最新记录。
我正在使用以下查询:
Select Top (1) * from student_data order by modified_date desc, created_date desc
但它不起作用,因为修改日期可以为null。
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
答案 0 :(得分: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 ;
答案 1 :(得分: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
答案 2 :(得分:0)
请尝试使用以下查询
Select Top (1) * from student_data order by coalesce(modified_date, created_date) desc