Try   HackMD

1873. Calculate Special Bonus

本題主要考驗 case when 用法

Calculate Special Bonus

透過leetcode 1873Calculate Special Bonus來練習

使用table

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

employee_id 是該表的主鍵。
該表的每一行表示員工 ID、員工姓名和薪水。

題目說明:

編寫 SQL 查詢來計算每個員工的獎金。如果員工的ID是奇數,並且員工姓名不以'M'字元開頭,則員工的獎金是他們的工資。其餘為0。

返回按 排序的結果表。employee_id

查詢結果格式如以下範例所示。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

解題:

以下為第一個例題

  1. 先以 case when ( employee_id % 2 ) = 0 判斷資料是否為奇數
  2. 在抓出 substring(name,1,1) = 'M' 字首為 'M' 的員工
select employee_id employee_id, case when ( employee_id % 2 ) = 0 then 0 when substring(name,1,1) = 'M' then 0 else salary end bonus from Employees order by employee_id