4 line solution using if statement


  • 5
    Z

    select
    if(id < (select count(*) from seat), if(id mod 2=0, id-1, id+1), if(id mod 2=0, id-1, id)) as id, student
    from seat
    order by id asc;


  • 0
    K

    GREAT JOB!!!


  • 1
    Y

    use 2 if() instead of 3:

    select if (

    id%2 <>0,
    if( id<> (select max(id) from seat), id+1, id),
    id-1

    ) id, student from seat order by id;


  • 3
    L
    SELECT
    	CASE
    		WHEN seat.id % 2 <> 0 AND seat.id = (SELECT COUNT(*) FROM seat) THEN seat.id
    		WHEN seat.id % 2 = 0 THEN seat.id - 1
    		ELSE
    			seat.id + 1
    	END as id,
    	student 
    FROM seat
    ORDER BY id
    ;
    

    Does anyone know how to use IF statement in TSQL? I have to use CASE here. Thank you.


  • 0
    D

    I did:

    select if(id < (select count(*) from seat), id + 2 * mod(id,2) - 1, id+mod(id,2)-1) as id, student
    from seat
    order by id
    

    Although @ykyk's solution looks a little better depending on how the compiler executes it.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.