• 【leetcode】Exchange Seats


    Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids.
    
    The column id is continuous increment.
    Mary wants to change seats for the adjacent students.
    Can you write a SQL query to output the result for Mary?
    +---------+---------+
    |    id   | student |
    +---------+---------+
    |    1    | Abbot   |
    |    2    | Doris   |
    |    3    | Emerson |
    |    4    | Green   |
    |    5    | Jeames  |
    +---------+---------+
    For the sample input, the output is:
    +---------+---------+
    |    id   | student |
    +---------+---------+
    |    1    | Doris   |
    |    2    | Abbot   |
    |    3    | Green   |
    |    4    | Emerson |
    |    5    | Jeames  |
    +---------+---------+
    Note:
    If the number of students is odd, there is no need to change the last one's seat.

    解题思路:这个题目难度不大,第一眼看起来也许觉得有些繁琐,但是如果抽丝剥茧,将解题过程分解成以下几步,就会豁然开朗。

    1.把所有奇数行的名字换成相邻的偶数行的名字。

    select a.id,b.student from seat a left join seat b on a.id & 1  and a.id + 1 = b.id;

    2.把所有偶数行的名字换成相邻的奇数行的名字。

    select a.id,b.student from seat a left join seat b on a.id & 1 = 0  and a.id  - 1 = b.id;

    3.合并1和2的结果

     select a.id,b.student  from seat a left join seat b
     on  (case when a.id & 1 then  a.id + 1 = b.id  else a.id -1 = b.id end);

    4.如果总行数为奇数,最后一行的名字不用替换。修正SQL如下:

    select a.id,case when b.student is null then a.student else b.student end  as student from seat a left join seat b
     on  (case when a.id & 1 then  a.id + 1 = b.id  else a.id -1 = b.id end);
  • 相关阅读:
    ResNet & DenseNet
    82. 删除排序链表中的重复元素 II
    C++ Primer 笔记——多重继承与虚继承
    C++ Primer 笔记——命名空间
    C++ Primer 笔记——异常处理
    C++ Primer 笔记——模板与泛型编程
    C++ Primer 笔记——转发
    C++ Primer 笔记——理解std::move
    C++ Primer 笔记——OOP
    C++ Primer 笔记——重载运算
  • 原文地址:https://www.cnblogs.com/seyjs/p/7591423.html
Copyright © 2020-2023  润新知