SQL交換一列中數據的值(如男女性別)
阿新 • • 發佈:2017-10-12
have set iat table p s 題目 highlight running 女性
在刷LeetCode的時候遇到的SQL題目
627. Swap Salary
Given a table salary
, such as the one below, that 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 temp table.
For example:
| id | name | sex | salary | |----|------|-----|--------| | 1 | A | m | 2500 | | 2 | B | f | 1500 | | 3 | C | m | 5500 | | 4 | D | f | 500 |
After running your query, the above salary table should have the following rows:
| id | name | sex | salary | |----|------|-----|--------| | 1 | A | f | 2500 | | 2 | B | m | 1500 | | 3 | C | f | 5500 | | 4 | D | m | 500 |
大概就是要求交換表中sex列的性別
一開始想著用update salary set sex = f when sex = m再用個AND,後來一想這樣執行的結果應該是錯的、
然後就偷看了solution,才知道還有when case語句,所以記錄一下
update salary set sex = case sex when ‘m‘ then ‘f‘ else ‘m‘ end;
大概意思就是when m,then就設置為f,,else都設置為m
SQL交換一列中數據的值(如男女性別)