我有一个名为Order的表 -
这给了我一栏 -
select min(OrderDate) from "order"
但是我想查看该记录的所有列。
任何帮助表示赞赏,
由于
答案 0 :(得分:2)
SELECT *
from [order]
WHERE OrderDate = (SELECT min(OrderDate) from [order])
答案 1 :(得分:1)
使用order by
沙top
:
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;
答案 2 :(得分: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.