2012-04-12 48 views
0

有序的表TOP 1的結果我有一個表是這樣的:選擇從外地

id    package    start_date   option 
1    342323    2012-02-02   1 
2    3423333    2012-02-06   1 
3    552234    2012-02-14   2 

我想只選擇(top 1)行具有minimum start_date。我試過where start_date = MIN(start_date)但它不工作。

我使用SQL Server 2008的

+1

做什麼用的關係做MSSQL 2008服務器 – pufos 2012-04-12 06:41:34

回答

4
select top 1 * from table 
order by start_date 
+0

謝謝...我沒有;沒有意識到這一點......所以..在加入中使用它..我必須做'交叉應用'吧? – pufos 2012-04-12 06:43:54

+0

@pufos我不知道該怎麼回答......你可以只從'tbl1 join(this_query)s'選擇* ...這是一個相當普遍的問題:) – 2012-04-12 06:47:49

+0

如果我使用'join(select top 1 * ...)'它贏了; t返回任何東西:因爲'top 1'... – pufos 2012-04-12 06:53:10

1

對於SQL Server

select top 1 * from tbl_name order by start_date 

對於MySQL

select * from tbl_name order by start_date asc limit 1 
+1

實際上,這在MySQL和PostgreSQL中是有效的,而不是在SQL Server中:( – 2012-04-12 06:49:24

+1

是原始帖子 – sujal 2012-04-12 06:52:59

1

嘗試:

where start_date = (select min(start_date) from yourtable) 
1
SELECT * FROM myTable 
ORDER BY start_date ASC 
LIMIT 1 
+0

其實,這在MySQL和PostgreSQL中是有效的,而不是在SQL Server中有效):( – 2012-04-12 06:48:50

+1

@MostyM ostacho你是真的,但用戶更新了我們的答案後的問題:) – DonCallisto 2012-04-12 06:49:48

1
SELECT * from Yourtable 
WHERE start_date = (SELECT (Min(yt1.Start_Date) FROM YourTable as yt1) 
+0

爲什麼你做兩個選擇?用'TOP'和'LIMIT'你可以得到相同的結果,以一種有效的方式... – DonCallisto 2012-04-12 06:44:26

+0

完全同意,但我認爲這可以是大選擇的一小部分,在這種情況下有可能TOP和LIMIT可以無法使用 – 2012-04-12 06:56:35

1

對於MSSQL

select top 1 * from your_table order by start_date asc 
0

此SQL Server特定的查詢應該得到你想要的數據。嘗試使用這樣的:

select top 1 * from tbl_name order by start_date asc 
0

您還可以使用:

;With top_record as 
(
SELECt * 
    ,row_number() OVER (order by start_date ASC) as row 
    FROM yourtable 
) 
SELECT * from top_record WHERE row = 1 

這將然後給你的靈活性,以確定使用DENSE_RANK/RANK而不是ROW_NUMBER()