让数字显示字的sql
C:/Users/bobo/AppData/Local/YNote/data/qq1BD99A3C386BF33BC41A3E78A77E7734/2698c116efe5423980e1e1395409b41c/i%5B35%7Exc2qdob.png
使用三目运算可以
C:/Users/bobo/AppData/Local/YNote/data/qq1BD99A3C386BF33BC41A3E78A77E7734/5f6a2d9db0bd43acbef159186eabfd51/6ihqynhx_z89.png
也可以写SQL
select *,
case sgroup
when 1 then N'组1'
when 2 then N'组2'
when 3 then N'组3'
else N'未知' end groupname
from @stuinfo
===========
本题SQL
select a.StandardId,a.StandardType, case StandardStatus
when 1 then N'作废'
when 2 then N'现行有效'
when 3 then N'即将实施'";
else N'未知' end groupname,
a.StandardTitle,a.ImplementationDate,a.ReleaseDate from OATestStandard a
SQL学习地址 https://www.cnblogs.com/4littleProgrammer/p/4820006.html
快下班了,抽点时间总结一下sql 的 case 用法。
sql 里的case的作用: 用于计算条件列表的表达式,并返回可能的结果之一。sql 的case 类型于编程语言里的 if-esle if-else 或者 switch,但它不用于控制sql程序的执行流程,而是作为列的逻辑使用。
语法:
case [input_expression]
when when_expression then result_expression
[...n]
[else else_result_expression]
end
注:其中[]内都是可选的。
准备测试数据:
1
2
3
4
5
6
7
8
9
10
11
12
| declare @stuinfo table
(id int,
sname nvarchar(20),
gender varchar(1),
sgroup int)
insert into @stuinfo
select 1,'张三','m',1 union all
select 2,'李四','f',1 union all
select 3,'王五','f',2 union all
select 4,'赵六','m',3 union all
select 5,'黄七','m',3
|
1. case后加表达式
根据表达式结果返回。
1
2
3
4
5
6
7
| select *,
case sgroup
when 1 then N'组1'
when 2 then N'组2'
when 3 then N'组3'
else N'未知' end groupname
from @stuinfo
|
2. case 后不加表达式
不加表达式,则根据when的条件返回。
| select *,
case
when sgroup = 1 and gender = 'm' then N'第一组男生'
when sgroup = 1 and gender = 'f' then N'第一组女生'
when sgroup = 2 and gender = 'm' then N'第二组男生'
when sgroup = 2 and gender = 'f' then N'第二组女生'
when sgroup = 3 and gender = 'm' then N'第三组男生'
when sgroup = 3 and gender = 'f' then N'第三组女生'
else N'未知' end comment
from @stuinfo
|
3. 用于 order by
如果存储过程需要支持多种排序,可以传递一个参数变量,然后根据该变量判断即可。
1
2
3
4
5
6
7
| declare @orderby int
set @orderby = 1
select * from @stuinfo
order by
case when @orderby = 1 then id end desc,
case when @orderby = 2 then id end
|
这里要用多个case,因为desc需要放在end 后面,否则会有语法错误。
4、示例:
select a.ApplyId,a.Code,a.CostItemId,a.CostItemName,a.CreatedDate,a.CreatedUserId,a.EquipmentCategroyId,a.Flag,a.FlowTime,a.Name,a.ParentId,a.PassingUserId,a.PassingUserIds,a.PassingUserNames,a.ProjectId,a.Remark,a.Spec,a.Unit, b.*, c.Code as ParentCode, c.Name as ParentName, case a.ImportFlag when 0 then '未导入' when 1 then '已导入' end as ImportFlag from EquipmentCategoryApply as a
inner join ProjectViewForJoin as b on a.ProjectId = b.ProjectIdForJoin
inner join EquipmentEquipmentCategory as c on a.ParentId = c.EquipmentCategoryId
|