SQL interchange values for data in a column (such as gender)

Source: Internet
Author: User
Tags case statement

The SQL problem encountered while brushing the Leetcode

627. Swap Salary

Given a table salary , such as the one below, which has M=male and F=female values. Swap all F and M values (i.e., change all F values to M and vice versa) with a single update query and no intermediate tem P table.

For example:

| ID | name | sex | Salary | | ----|------|-----|--------|| 1  | A    | m   | 2500   | | 2  | B    | f   | | |   3  | C    | m   | 5500   | | 4  | D | f | |    

After running your query, the above salary table should has the following rows:

| ID | name | sex | Salary | | ----|------|-----|--------|| 1  | A    | f   | 2500   | | 2  | B    | m   | | |   | 3  | C    | f   | 5500   | | 4  | D |    m   | |    

Probably asking for sex in the exchange table.

At first I wanted to use update salary set sex = f when sex = M again with an and and then the result of this implementation should be wrong,

And then just peek at the solution, just know there is a case statement, so record

Update Salary   Set =        Case Sex            when ' m '  Then ' F '          Else ' m '      End

It means that when M,then is set to F,,else, it is set to M

SQL interchange values for data in a column (such as gender)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.