1. 程式人生 > 其它 >LeetCode(SQL):1873. 計算特殊獎金

LeetCode(SQL):1873. 計算特殊獎金

提交程式碼

# Write your MySQL query statement below
SELECT employee_id,
	(case
		when  employee_id %2!=0 && name NOT LIKE 'M%'
			then salary
		ELSE salary=0 
		END) bonus
from employees

執行結果

執行結果:
通過
顯示詳情
新增備註

執行用時:
593 ms
, 在所有 MySQL 提交中擊敗了
60.01%
的使用者
記憶體消耗:
0 B
, 在所有 MySQL 提交中擊敗了
100.00%
的使用者
通過測試用例:
22 / 22

完整程式碼

sql建立

/*
Navicat MySQL Data Transfer

Source Server         : local
Source Server Version : 50519
Source Host           : localhost:3306
Source Database       : db_learn

Target Server Type    : MYSQL
Target Server Version : 50519
File Encoding         : 65001

Date: 2022-05-13 15:26:46
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `employees_1873`
-- ----------------------------
DROP TABLE IF EXISTS `employees_1873`;
CREATE TABLE `employees_1873` (
  `employee_id` int(11) NOT NULL DEFAULT '0',
  `name` varchar(255) DEFAULT NULL,
  `salary` int(11) DEFAULT NULL,
  PRIMARY KEY (`employee_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of employees_1873
-- ----------------------------
INSERT INTO `employees_1873` VALUES ('2', 'Meir', '3000');
INSERT INTO `employees_1873` VALUES ('3', 'Michael', '3800');
INSERT INTO `employees_1873` VALUES ('7', 'Addilyn', '7400');
INSERT INTO `employees_1873` VALUES ('8', 'Juan', '6100');
INSERT INTO `employees_1873` VALUES ('9', 'Kannon', '7700');

查詢

SELECT employee_id,
	(case
		when  employee_id %2!=0 && name NOT LIKE 'M%'
			then salary
		ELSE salary=0 
		END) bonus
from employees_1873

收穫

查詢時的case應如下,不能忘記END。

select name, (CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
    END) as xx4 
from table

condition中的取餘可以用%,也可以用MOD()。且可以用&&,也可以用and。
as可省略。