如何显示最新插入的记录?

时间:2015-05-14 10:01:24

标签: sql

我想在gridview显示最新插入的记录。

示例数据库:

Id  Alerts   Alert_Date
--  ------   ----------
1   Alert1   5/11/2015 12:12:22 PM
2   Alert2   5/11/2015 12:12:22 PM
3   Alert1   5/12/2015 12:12:22 PM
4   Alert2   5/13/2015 12:12:22 PM
5   Alert2   5/14/2015 12:12:22 PM
6   Alert3   5/14/2015 12:12:22 PM

预期输出:

Alerts    Alert_Date
------    ----
Alert1    5/12/2015 12:12:22 PM
Alert2    5/14/2015 12:12:22 PM
Alert3    5/14/2015 12:12:22 PM

SQL:

SELECT DISTINCT Alerts,
(SELECT TOP (1) tbl_Notifications.Alert_Date AS Expr1) AS Expr1
FROM tbl_Notifications

我尝试了上面给出的东西,但它没有用。帮我找一个合适的解决方案。谢谢。

2 个答案:

答案 0 :(得分:2)

尝试将GROUP BY子句与MAX函数一起使用,如下所示

SELECT Alerts, MAX(Alert_Date)
FROM tbl_Notifications
GROUP BY Alerts

答案 1 :(得分:2)

试试这个

SELECT TOP (1) Alert,Alert_Date AS Expr1 
FROM tbl_Notifications order by alert_date desc