![](/img/trans.png)
[英]SQL selecting the rows with the maximum value in a table ordered by a column from another
[英]Select rows from a SQL Server Database table only rows that have another column as the maximum
我正在尝试从Microsoft SQL Server数据库表中选择行,对于一列(ID)中的每个ID,仅选择具有另一列作为最大值的行(IDtoBeMaxed)。 例如:
从这张桌子
ID SomeValue IDtoBeMaxed
1 56 2
1 59 2
1 80 1
2 55 5
2 80 5
2 56 3
2 81 3
我只想要
ID SomeValue IDtoBeMaxed
1 56 2
1 59 2
2 55 5
2 80 5
我有这个查询有效,但我认为应该有一种更快的方法来减少查询的响应时间。 再次,这个查询给了我想要的东西,我正在寻找更快的响应时间查询。
SELECT *
FROM myTable
WHERE ID = 2
AND IDtoBeMaxed = (SELECT MAX(IDtoBeMaxed) FROM myTable WHERE ID = 2)
编辑:我不需要所有行,就像我在上面的例子中所示。 我只需要特定ID的行,就像我自己编写的查询一样。
结果:我尝试了Shavkat查询,但它并不比我写的查询快。 其余的答案返回我不想要的所有行。 所以这还有待讨论。 但是感谢你到目前为止的答案。
您是否尝试在一个查询中返回表中的所有行? 像下面这样的东西会起作用:
SELECT t.Id,t.SomeValue,t.IDtoBeMaxed
FROM MyTable t
JOIN (
SELECT Id,MAX(IDToBeMaxed) AS MaxId
FROM MyTable
GROUP BY Id
) AS m ON t.Id=m.Id AND t.IDToBeMaxed=m.MaxId
回复您的修改:
您编写的查询就像您可以获得的一样简单。 如果需要缩短响应时间,应该考虑在ID
和IDToBeMaxed
列上创建索引。
CREATE INDEX ix_IDMaxed ON MyTable(ID,IDToBeMaxed)
这是你的选择吗?
这是一个老派的:
declare @myTable table (ID int, SomeValue int, IDtoBeMaxed int)
insert into @myTable
values
(1, 56, 2 ),
(1, 59, 2 ),
(1, 80, 1 ),
(2, 55, 5 ),
(2, 80, 5 ),
(2, 56, 3 ),
(2, 81, 3 ),
(3, 55, 5 ),
(3, 80, 5 ),
(3, 56, 5 ),
(3, 81, 5 )
select a.*
from @myTable a left join @myTable b
on a.ID = b.ID and a.IDtoBeMaxed < b.IDtoBeMaxed
where b.ID is null and a.ID = 2
你可以试试下面......
WITH selectOne
AS ( SELECT ROW_NUMBER() OVER ( PARTITION BY SomeValue, ID ORDER BY IDtoBeMaxed DESC ) AS RowNum ,
ID ,
SomeValue ,
IDtoBeMaxed
FROM myTable
)
SELECT *
FROM selectOne
WHERE RowNum = 1
以下示例返回按IDtoBeMaxed排名的记录
;WITH cte AS
(SELECT *, DENSE_RANK() OVER(PARTITION BY ID ORDER BY IDtoBeMaxed DESC) AS dr
FROM myTable
)
SELECT *
FROM cte
WHERE dr = 1
在SQLFiddle
演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.