T-SQL顺序依据,基于其他列值

时间:2014-05-01 17:42:59

标签: sql-server sql-server-2008 tsql

我坚持一个应该非常简单的查询,但由于原因不明,我的大脑不在这里打球......

表格

id(int) | strategy (varchar) | value (whatever)
1         "ABC"                whatevs
2         "ABC"                yeah
3         "DEF"                hello
4         "DEF"                kitty
5         "QQQ"                hurrr

查询应选择按策略分组的所有行,但每个策略只选择一行 - 具有最高ID的行。

在上面的情况中,它应该返回id为2,4和5的行

5 个答案:

答案 0 :(得分:1)

SELECT id, strategy , value
FROM (
       SELECT id, strategy , value 
             ,ROW_NUMBER() OVER (PARTITION BY strategy ORDER BY ID DESC) rn
      FROM Table_Name
    ) Sub
WHERE rn = 1

Working SQL FIDDLE

答案 1 :(得分:1)

您可以使用窗口功能来获得所需的解决方案。小提琴here

with cte as
(
select 
 rank()over(partition by strategy order by id desc) as rnk,  
  id, strategy, value from myT 
)
select id, strategy, value from 
cte where rnk = 1;

答案 2 :(得分:0)

试试这个:

SELECT T2.id,T1.strategy,T1.value
FROM TableName T1
INNER JOIN
(SELECT MAX(id) as id,strategy
 FROM TableName
 GROUP BY strategy) T2
ON T1.id=T2.id

结果:

ID  STRATEGY    VALUE
2   ABC         yeah
4   DEF         kitty
5   QQQ         hurrr

请参阅SQL Fiddle中的结果。

答案 3 :(得分:0)

SELECT id, strategy , value
FROM (
       SELECT id, strategy , value 
             ,MAX(id) OVER (PARTITION BY strategy) MaxId
      FROM YourTable
    ) Sub
WHERE id=MaxId

答案 4 :(得分:0)

你也可以试试这个:

SELECT id, strategy, value FROM TableName WHERE id IN (
    SELECT MAX(id) FROM TableName GROUP BY strategy
) 

比特取决于您的数据,您可能会更快地获得结果,因为它不进行排序,但另一方面它使用IN,如果有很多策略可以减慢你的速度&#39; < / p>