Table creation Create table 'Lil '( 'Id' int (10) not null AUTO_INCREMENT, 'Name' char (20) default null, 'Birthday' datetime default null, Primary key ('id') ENGINE = InnoDB default charset = utf8 Data insertion: Insert into lee (name, birthday) values ('Sam ', '2017-01-01 '); Insert into lee (name, birthday) values ('Lee ', '2017-01-01 '); Insert into lee (name, birthday) values ('John', '2017-01-01 '); First usage: SELECT name, Case when birthday <'000000' THEN 'old' WHEN birthday> '123' THEN 'Yong' ELSE 'OK' END YORN FROM lee
Second usage: Select name, CASE name WHEN 'Sam 'Then 'Yong' WHEN 'Lee 'then' hands' ELSE 'good' END as oldname FROM lee
Third: of course, the case when Statement can be composite. Select name, birthday, Case When birthday> '123' then 'Yong' When name = 'Lee 'then' handsome' Else 'just so so' end From lee;
If you use an SQL statement to compare dates, you need to quote the year. Otherwise, the results may be different from the expected results, Of course, you can also use the year function to implement Select name, Case when year (birthday)> 1988 then 'Yong' When year (birthday) <1980 then 'old' Else 'OK' END From lee; ========================================================== ============================ Create table penalties ( Paymentno INTEGER not NULL, Payment_date DATE not null, Amount DECIMAL (7,2) not null, Primary key (paymentno) ) Insert into penalties values (1, '2017-01-01 ', 2008 ); Insert into penalties values (2, '2017-01-01 ', 2009 ); Insert into penalties values (3, '2017-07-01 ', 2008 ); Question 1: There are three types of fine registration: The first category of low, including fines greater than 0 and less than or equal to 40, and the second category of moderate fines between 40 and 80, category 3 high includes all fines greater than 80 Select payment_date, amount, Case When amount> = 0 AND amount <40 then 'low' When amount> = 40 AND amount <80 then 'moderate' When amount> = 80 then 'high' Else 'null' END FROM penalties Question 2: calculate the number of low fines Select * from (Select paymentno, amount, Case When amount> = 0 AND amount <40 then 'low' When amount> = 40 AND amount <80 then 'moderate' When amount> = 80 then 'high' Else 'encrect 'end lvl From penalties) as p Where p. lvl = 'low'
|