SQL Server按个案排序

时间:2017-06-05 22:01:38

标签: sql-server database sql-server-2014

我想使用此query

创建第四列
select * from (select ID, column0, column1, column2, column3 = Case when 
column2 = '' then column1 else column2 end, row_number() over(partition by 
column0 order by [column3]) as column4 from myTable) ti 

但是出现了这个错误:

Invalid column name 'column3'.

我想要这个结果:(红色标记列):

Example

2 个答案:

答案 0 :(得分:1)

您需要从子查询外部使用order by,如下所示:

Select *, row_number() over(partition by 
 column3 order by [Id]) as column4 
 from (select ID, column0, column1, column2, column3 = Case when 
      column2 = '' then column1 else column2 end 
        from myTable) ti 

对于图像中的第4列,您需要按ID3分列。如果您按列0进行分区,那么您将获得所有1的

答案 1 :(得分:0)

这样就可以了:

select *, row_number() over(partition by 
column0 order by [column3]) as column4 from 
(select ID, column0, column1, column2, column3 = Case when 
column2 = '' then column1 else column2 end from myTable) ti