用于最低时间行的SQL查询

时间:2010-02-01 17:19:28

标签: sql sql-server performance datetime

我有一个包含一个DateTime列的表。我想找到时间最短的行,它们的时间大于变量myTime。 我怎样才能做到这一点? 什么样的指数会提高绩效?

4 个答案:

答案 0 :(得分:2)

使用TOP(SQL Server 2000 +)


SELECT t.*
  FROM TABLE t
 WHERE t.date_time_col = (SELECT TOP 1
                                 x.date_time_col
                            FROM TABLE x
                           WHERE CONVERT(hh, x.date_time_col, 8) < @myTime
                        ORDER BY x.date_time_col)

使用MIN


SELECT t.*
  FROM TABLE t
 WHERE t.date_time_col = (SELECT MIN(x.date_time_col)
                            FROM TABLE x
                           WHERE CONVERT(hh, x.date_time_col, 8) < @myTime)

假设在DATETIME列上存在一个索引,因为使用了一个函数 - 数据类型正在被更改。

答案 1 :(得分:1)

SELECT DateTime1
FROM Table1
WHERE DateTime1 = (
    SELECT MIN(DateTime1)
    FROM Table1
    WHERE DateTime1 > @myTime);

或:

SELECT T1.DateTime1
FROM Table1 AS T1
JOIN (
    SELECT MIN(DateTime1) AS DateTime1
    FROM Table1
    WHERE DateTime1 > @myTime) AS T2
ON T1.DateTime1 = T2.DateTime1;

运行两者以查看哪个最快。在DateTime1上使用索引。

测试数据以检查它是否有效:

CREATE TABLE Table1 (DateTime1 NVARCHAR(100) NOT NULL);
INSERT INTO Table1 (DateTime1) VALUES
('2010-02-01 17:53'),
('2010-02-01 17:55'),
('2010-02-01 17:55'),
('2010-02-01 17:56');

答案 2 :(得分:1)

那样的话......

DECLARE @temp datetime

SET @temp = (SELECT GETDATE())

Select myCol from MyTable where MyColWithDate IN (SELECT top 1 MyCol, MyCol2 FROM MyTable WHERE MyColWithDate > @temp ORDER BY MyColWithDate ASC)

或者我可能会选择MIN

Select myCol from MyTable where MyColWithDate IN (SELECT MIN(MycolWithDAte) FROM MyTable WHERE MyColWithDate > @temp GROUP BY MyColWithDate)

答案 3 :(得分:0)

DECLARE @temp datetime

SET @temp = (SELECT GETDATE())

SELECT MyCol, MyCol2 FROM MyTable WHERE MyColWithDate > @temp ORDER BY MyColWithDate ASC

关于它所依赖的索引,您可以告诉我们有关您要执行的操作的更多信息。 否则,你可以为上面的例子索引MyColWithDate。