How to sort values in columns and update table?

前端 未结 7 2544
花落未央
花落未央 2020-12-05 15:28

I\'m completely new to sql and can\'t do that myself. So I need your help. I want to sort values in column and then save changes. But I don\'t know how to do that.

T

7条回答
  •  旧时难觅i
    2020-12-05 15:40

    you can sort on two fields at the same time.

    SELECT *
    FROM games
    ORDER BY id DESC, name ASC
    

    I don't understand what you mean by save changes in the table. The ORDER BY, is just changing the display that you are looking at it doesn't change the data in the table unless you perform an UPDATE.

    If you are unfamiliar with SQL, there are a lot of tutorials online that can help:

    SQL Course

    Beginner SQL Tutorial

    SQL Tutorial - Learn SQL

    Edit based on the comments, this can be done in one step:

    create table #temp
    (
        id int,
        name varchar(50),
        somedesc varchar(50)
    )
    
    insert into #temp values (1, 'best', 'desc1')
    insert into #temp values (2, 'worth', 'desc2')
    insert into #temp values (3, 'good', 'desc3')
    
    update t1
    SET t1.id = t2.rn
        , t1.somedesc = t1.somedesc
    FROM #temp t1
    JOIN 
    (
        select id, name, somedesc, row_number() over(order by name, id) as rn
        from #temp 
    ) t2
    on t1.id = t2.id
    
    select *
    from #temp
    order by id
    
    drop table #temp
    

提交回复
热议问题