Search code examples
sql-serverdatabasesql-server-2014

SQL Server order by case


I want to create a fourth column with this 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 

But this error appears:

Invalid column name 'column3'.

I want this result: (red marked column):

Example


Solution

  • you need to use order by from outside of subquery as below:

    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 
    

    For your 4th column in image you need to partition by column3 order by id. If you do Partition by column0 then you will get all 1's