SQL,多个if语句,然后呢?
我是SQl新手,尝试自己学习。
我正在学习SQL中if和else语句的用法
这里是我正在尝试使用的数据,如果在下表中,或者声明,我希望根据年龄使用sql查询更新评论,假设年龄在22到25之间,评论“下毕业”
Age: 26 to 27, comments " post graduate"
Age: 28 to 30, comments "working and single"
Age: 31 to 33, comments " middle level manager and married"
表名:人员
personid lastname firstname age comments
1 Cardinal Tom 22
2 prabhu priya 33
3 bhandari abhijeet 24
4 Harry Bob 25
5 krishna anand 29
6 hari hara 31
7 ram hara 27
8 kulkarni manoj 35
9 joshi santosh 28
如何使用案例
试用CASE声明
Select personid,lastname,firstname,age,
Case when age between 26 and 27 then 'post graduate'
when age between 28 and 30 then 'working and single'
when age between 31 and 33 then ' middle level manager and married'
Else 'Nil'
End comments
from persons
我可能会去CASE声明
就像是
SELECT *,
CASE
WHEN age BETWEEN 22 AND 25
THEN 'under graduate'
WHEN age BETWEEN 26 AND 27
THEN 'post graduate'
WHEN age BETWEEN 28 AND 30
THEN 'working and single'
WHEN age BETWEEN 31 AND 33
THEN 'middle level manager and married'
ELSE 'TADA'
END Comment
FROM persons
按照您的要求,我们不能使用if ... else语句。 Case..when声明将是最合适的一个。 另一件事我们无法在任何查询中使用if ... else(我的意思是在选择,插入,更新内)。
和你的
Select personid,lastname,firstname,age,
Case when age between 26 and 27 then 'post graduate'
Case when age between 28 and 30 then 'working and single'
Case when age between 31 and 33 then ' middle level manager and married'
Else 'Nil'
End comments
from persons
链接地址: http://www.djcxy.com/p/94359.html