是否可以编写查询以查找没有JOIN且没有ORDER BY的最大记录?

时间:2013-03-02 20:06:22

标签: sql-server tsql

更新 - 问题

是否有更强更紧凑的方法来编写一个从表中选择最大记录的查询,而不是使用自联接?

一个示例是可能具有以下架构的事件表:

   EventID | EventType | Timestamp | Description
-----------+-----------+-----------+--------------
   INT     | VARCHAR   | INT       | VARCHAR

并且可能包含每种类型事件的多条记录。让我们说:

     1     |    A      |  100000   | 'First Event'
     2     |    A      |  100005   | 'Second Event'
     3     |    B      |  100009   | 'Third Event'
     4     |    A      |  100009   | 'Fourth Event'
     5     |    B      |  100010   | 'Fifth Event'
     6     |    B      |  100030   | 'Sixth Event'
     7     |    A      |  100030   | ' ... '
     8     |    C      |  100030   | ' ... '
     9     |    C      |  100050   | ' ... '

让我们说我想知道每种类型的最新事件是什么 - 事件#6,#7和#9。然后我必须编写一个如下所示的查询:

SELECT EventID
     , EventType
     , Timestamp
     , Description
  FROM EventsTable T
 INNER JOIN (SELECT EventType
                  , MAX(Timestamp) 
               FROM EventsTable TInner
              GROUP BY EventType) TSelf
         ON T.Timestamp = TSelf.Timestamp
         AND T.EventType = TSelf.EventType

所以问题归结为:是否有更简洁的方式来表达相同的查询,理想情况下无需求助于

4 个答案:

答案 0 :(得分:1)

试试这个..

SELECT EventID, EventType, Timestamp, Description
FROM EventsTable
WHERE EventType = 'B' AND 
      Timestamp = (SELECT max(Timestamp) FROM EventsTable WHERE EventType = 'B');

答案 1 :(得分:0)

SELECT EventID, EventType, Timestamp, Description
FROM EventsTable T
WHERE T.EventType = 'B'
ORDER BY Timestamp
LIMIT 1

应该做的伎俩(对于支持LIMIT的DBMS)。

答案 2 :(得分:0)

  

没意识到你只需要返回一行。使用Common Table Expression可以获得所需的结果。简单而清洁。

;WITH CTE
AS
(
    SELECT EventID, 
           EventType, 
           Timestamp,
           Description
    FROM EventsTable 
    WHERE EventType = 'B'
)

SELECT TOP 1 * FROM CTE 
ORDER BY TIMESTAMP DESC

答案 3 :(得分:0)

如果您不想使用此命令来使用订单:

SELECT * FROM EventsTable WHERE EventType = 'B' AND
Timestamp = (SELECT Max(Timestamp) FROM EventsTable WHERE EventType = 'B');

如果顺序没问题:

MySQL的:

SELECT * FROM EventsTable WHERE EventType = 'B' ORDER BY Timestamp DESC LIMIT 1;

Sql Server:

SELECT TOP 1 * FROM EventsTable WHERE EventType = 'B' ORDER BY Timestamp DESC

Plz见fiddle