SQL Server:只select具有MAX(DATE)的行
我有一个数据表(数据库是MSSQL):
ID OrderNO PartCode Quantity DateEntered 417 2144 44917 100 18-08-11 418 7235 11762 5 18-08-11 419 9999 60657 100 18-08-11 420 9999 60657 90 19-08-11
我想做一个查询,返回OrderNO,PartCode和数量,但只为最后注册的订单。
从示例表中,我想回到以下信息:
OrderNO PartCode Quantity 2144 44917 100 7235 11762 5 9999 60657 90
请注意,订单9999只返回一行。
谢谢!
如果rownumber() over(...)
可用于您….
select OrderNO, PartCode, Quantity from (select OrderNO, PartCode, Quantity, row_number() over(partition by OrderNO order by DateEntered desc) as rn from YourTable) as T where rn = 1
最好的方法是Mikael Eriksson,如果ROW_NUMBER()
可用。
其次,根据Cularis的回答,join一个查询。
或者,最简单直接的方法是WHERE子句中的相关子查询。
SELECT * FROM yourTable AS [data] WHERE DateEntered = (SELECT MAX(DateEntered) FROM yourTable WHERE orderNo = [data].orderNo)
要么…
WHERE ID = (SELECT TOP 1 ID FROM yourTable WHERE orderNo = [data].orderNo ORDER BY DateEntered DESC)
select OrderNo,PartCode,Quantity from dbo.Test t1 WHERE EXISTS(SELECT 1 FROM dbo.Test t2 WHERE t2.OrderNo = t1.OrderNo AND t2.PartCode = t1.PartCode GROUP BY t2.OrderNo, t2.PartCode HAVING t1.DateEntered = MAX(t2.DateEntered))
这是上面提供的所有查询中最快的。 查询成本为0.0070668。
以上由Mikael Eriksson提供的首选答案的查询成本为0.0146625
你可能不关心这样一个小样本的性能,但在大型查询中,这些都加起来了。
SELECT t1.OrderNo, t1.PartCode, t1.Quantity FROM table AS t1 INNER JOIN (SELECT OrderNo, MAX(DateEntered) AS MaxDate FROM table GROUP BY OrderNo) AS t2 ON (t1.OrderNo = t2.OrderNo AND t1.DateEntered = t2.MaxDate)
内部查询select所有OrderNo
及其最大date。 要获取表格的其他列,可以在OrderNo
和MaxDate
上join它们。
对于MySql,你可以做如下的事情:
select OrderNO, PartCode, Quantity from table a join (select ID, MAX(DateEntered) from table group by OrderNO) b on a.ID = b.ID
你也可以使用select语句作为左连接查询…例如:
... left join (select OrderNO, PartCode, Quantity from (select OrderNO, PartCode, Quantity, row_number() over(partition by OrderNO order by DateEntered desc) as rn from YourTable) as T where rn = 1 ) RESULT on ....
希望这有助于search这个:)
尽量避免IN使用JOIN
SELECT SQL_CALC_FOUND_ROWS * FROM (SELECT msisdn, callid, Change_color, play_file_name, date_played FROM insert_log WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent') ORDER BY callid ASC) t1 JOIN (SELECT MAX(date_played) AS date_played FROM insert_log GROUP BY callid) t2 ON t1.date_played=t2.date_played
rownumber()在(…)正在工作,但我不喜欢这个解决scheme的2个原因。 – 当你使用像SQL2000这样旧版本的SQL时,这个function是不可用的 – 对函数的依赖性并不可读。
另一个解决scheme是
SELECT tmpall.[OrderNO] , tmpall.[PartCode] , tmpall.[Quantity] , FROM (SELECT [OrderNO], [PartCode], [Quantity], [DateEntered] FROM you_table) AS tmpall INNER JOIN (SELECT [OrderNO], Max([DateEntered]) AS _max_date FROM your_table GROUP BY OrderNO ) AS tmplast ON tmpall.[OrderNO] = tmplast.[OrderNO] AND tmpall.[DateEntered] = tmplast._max_date