通过分区而不重新排序数据

时间:2019-05-02 00:15:01

标签: sql sql-server

我当前的数据如下:

Current Data

我希望数据成为

I want this Data

当我使用row_number函数时,它会重新排序,并给我错误的row_number,如下所示

Wrong Result

如果我们看到“调整后的转化成本”值0.160即将出现在结果的顶部,并且编号为1,那么根据第一个屏幕截图,该值应该为3

谢谢

1 个答案:

答案 0 :(得分:0)

MYSQL使用变量

结果-http://www.sqlfiddle.com/#!9/406f64/8/0

select 
colo1,f7,
if(colo1='Total Adj. Conversion Spend',@initVal:=@initVal+1,1) as RowNumber
from temp,(select @initVal:=0) vars


使用排名和行号的MS-SQL
我使用Row_Number()保留顺序,然后在case语句中使用Rank()
http://www.sqlfiddle.com/#!18/fde9f/15/0

select subquery_1.colo1,subquery_1.f7
,case when subquery_1.colo1='Total Adj. Conversion Spend' then 
rank() over (partition by colo1 order by rownum) else 1 end as rnk
from
(select *,row_number() OVER (ORDER BY (Select 0)) as rownum from temp) as subquery_1
order by subquery_1.rownum