2015-04-07 34 views

回答

2
SELECT * 
from [order] 
WHERE OrderDate = (SELECT min(OrderDate) from [order]) 
+0

完美的作品,謝謝M.Ali,不知道爲什麼有人給你一個負面的... – Vlad11

+0

不用擔心,很高興它有幫助,我不擔心倒票,有一些小丑放鬆在那裏:) –

1

使用order bytop

select top 1 o.* 
from orders o 
order by orderdate asc; 

編輯:

如果你想重複使用with ties

select top 1 with ties o.* 
from orders o 
order by orderdate asc; 
+1

這將只返回最上面的1行,如果有多行,OrderDate = min(OrderDate)' –

+0

@ M.Ali。 。 。這個問題用單數表示:「該記錄的所有列」。無論如何,使用'with tie'來獲取所有具有相同值的行是很容易的。 –

1

雖然M. Ali's answer是準確的,但根據表的大小和索引配置,可能會導致性能下降。它需要兩次讀取表格。

在SQL Server 2005及更高版本上,可以使用窗口函數並將計劃限制爲通過表單讀取。對於非常小的數據集,查詢成本實際上更高,但讀取次數減半。對於大型數據集,這應該會導致顯着優異的性能。

代碼示例:

SET NOCOUNT ON; 

-- Populate Test Data 

DECLARE @Orders TABLE (OrderNum int IDENTITY, OrderDate datetime); 
INSERT INTO @Orders (OrderDate) VALUES ('2015-04-04'); 
INSERT INTO @Orders (OrderDate) VALUES ('2015-04-04'); 
INSERT INTO @Orders (OrderDate) VALUES ('2015-04-04'); 
INSERT INTO @Orders (OrderDate) VALUES ('2015-04-05'); 
INSERT INTO @Orders (OrderDate) VALUES ('2015-04-05'); 
INSERT INTO @Orders (OrderDate) VALUES ('2015-04-06'); 
INSERT INTO @Orders (OrderDate) VALUES ('2015-04-07'); 
INSERT INTO @Orders (OrderDate) VALUES ('2015-04-07'); 

-- Run Tests 

SET STATISTICS IO ON; 

PRINT 'Full Table'; 
SELECT * FROM @Orders; 

PRINT 'Results using MIN'; 
SELECT  * 
FROM  @Orders 
WHERE  OrderDate = (SELECT min(OrderDate) FROM @Orders); 

PRINT 'Results using RANK'; 
WITH BaseData AS 
(
    SELECT 
     *, 
     RANK() OVER (ORDER BY OrderDate) AS OrderDateRank 
    FROM  @Orders 
) 
SELECT  * 
FROM  BaseData 
WHERE  OrderDateRank = 1; 

SET STATISTICS IO OFF; 

SET NOCOUNT OFF; 

查詢費用:

MIN: 0.0065718

RANK: 0.014645

統計:

Full Table 
Table '#1E0C7C2B'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Results using MIN 
Table '#1E0C7C2B'. Scan count 2, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. 
Results using RANK 
Table '#1E0C7C2B'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.