2009-04-26 202 views
1

我有一個sql server 2008數據庫中包含一堆記錄以及日期列的表。當發生表格的新條目時,會自動插入日期。所以,它包含已經創建的記錄的日期。TSQL查詢將返回表中最早的日期和最新的日期

我想運行一個查詢,該查詢將返回此表中的最早日期和最新日期。

我試過類似的東西;

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'。

任何人都可以指導我如何做到這一點?

回答

3
SELECT 
     MIN(DateAdded) As FirstDate, 
     MAX(DateAdded) As LastDate 
FROM 
     News; 
1

答案是使用聚合。

SELECT 
    MIN(DateAdded) AS firstdate, 
    MAX(DateAdded) AS lastdate 
FROM 
    News; 

查詢返回2分的結果:每個作品單獨雖然

+0

謝謝你的回答,我標誌着何塞的答案,因爲他第一次和我寫的不想得罪任何人... – 2009-04-26 18:06:08

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