如何在sql server 2008 r2中创建查询

时间:2017-02-16 08:07:41

标签: sql-server sql-server-2008

我需要最终结果:

enter image description here

我用过

max(value) OVER (PARTITION BY name order by value) 

但在sql server 2008 r2中不支持

结果  第一个:'a'因为最大值而下一个记录都是'a'
第二个:'d'因为第二个最大值而下一个记录都是'd'

2 个答案:

答案 0 :(得分:0)

试试这个:

WITH cte1 AS (
    SELECT name, MAX(value) AS max_value
    FROM yourTable
    GROUP BY name
),
WITH cte2 AS (
    SELECT t.name, ROW_NUMBER() OVER (ORDER BY t.max_value DESC) rn
    FROM cte1 t
)
SELECT t1.name, t1.value
FROM yourTable t1
INNER JOIN cte2 t2
    ON t1.name = t2.name
ORDER BY t2.rn, t1.value DESC

答案 1 :(得分:0)

绝对是一个奇怪的要求,但下面的代码片段应该做你的工作 -

declare @t table(name varchar(1), value int)
insert into @t values('a',50),('b',11),('a',10),('d',33),('f',5),('b',3)
select name,value from @t
select name,value from @t order by case when name='a' then 1 when name='b' then 3 when name='d' then 2 when name='f' then 4 end,value desc