我在sql server 2008数据库中有一个表,其中包含一堆记录和一个日期列。当表的新条目出现时,将自动插入日期。因此,它包含已创建记录的日期。
我正在尝试运行一个查询,该查询会返回此表中最早的日期和最新日期。
我尝试了类似的东西;
SELECT TOP(1) DateAdded AS firstdate
FROM News
ORDER BY DateAdded DESC;
SELECT TOP(1) DateAdded AS lastdate
FROM News
ORDER BY DateAdded ASC;
但它只返回'firstdate'。
任何人都可以指导我如何实现这个目标吗?
答案 0 :(得分:3)
SELECT
MIN(DateAdded) As FirstDate,
MAX(DateAdded) As LastDate
FROM
News;
答案 1 :(得分:1)
答案是使用聚合。
SELECT
MIN(DateAdded) AS firstdate,
MAX(DateAdded) AS lastdate
FROM
News;
您的查询返回2个结果:每个结果单独工作
答案 2 :(得分:1)
您可以使用以下内容:
select DateAdded from (SELECT DateAdded,
row_number() over (order by DateAdded desc) as rn,
count(*) over () as added_value
FROM News
) t
where rn = 1
or rn = added_value
ORDER BY DateAdded DESC