case when用法sql

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了case when用法sql相关的知识,希望对你有一定的参考价值。

参考技术A

在SQL中,“Case When”语句用法如下:

在SQL中,“Case When”语句用于选择判断,在执行时先对条件进行判断,然后根据判断结果做出相应的操作;语法“CASE 字段 WHEN 条件1 THEN 操作1 WHEN 条件2 THEN 操作2...ELSE 操作n END;”。

SQL 是一种操作数据库的语言,包括创建数据库、删除数据库、查询记录、修改记录、添加字段等。SQL 虽然是一种被 ANSI 标准化的语言,但是它有很多不同的实现版本。

SQL 是 Structured Query Language 的缩写,中文译为“结构化查询语言”。SQL 是一种计算机语言,用来存储、检索和修改关系型数据库中存储的数据。

SQL 是关系型数据库的标准语言,所有的关系型数据库管理系统(RDBMS),比如 mysql、Oracle、SQL Server、MS Access、Sybase、Informix、Postgres 等,都将 SQL 作为其标准处理语言。

此外,SQL 也有一些变种,就像中文有很多方言,比如:

    微软的 SQL Server 使用 T-SQL;

    Oracle 使用 PL/SQL;

    微软 Access 版本的 SQL 被称为 JET SQL(本地格式)。

Sqlserver的case when 用法

select PayAmount from Table where ID=123,怎么用case when求PayAmount

 ---下文举例分析了case when常用的用法,如下所示:涉及排序字段的应用
 create table test
(
 qty int ,
 sort varchar(20)
)
insert into test(qty,sort)values
(1,'a'),(2,'b'),(3,'d'),(1,'e')
go
----方法1:
select sort,qty,
  case qty
    when 1 then '少'
    when 2 then '中'
    when 3 then '多'
    else '未知'
  end as [数量范围]
  from test 
--方法2:
select sort,qty,
  case 
    when qty=1 then '少'
    when qty=2 then '中'
    when qty=3 then '多'
    else '未知'
  end as [数量范围]
  from test 

---sum统计用法
select 
 sum( case      when qty=1 then 1 else 0 end) as [少],
 sum( case qty  when  2 then 1 else 0 end) as [中],
 sum( case      when qty=3 then 1 else 0 end) as [多],
 sum( case      when qty<> 1 and qty <>2 and qty <>3 then 1 else 0 end) as [位置]
    from test 
  
 
 ---case when 做排序字段
 declare @i int 
 set @i=0
 select * from test 
 order by 
 case @i when 0 then qty else sort    end 
   
 

go
truncate table test
drop     table test

追问

哇 !

参考技术A 你直接取出来就好了啊,你要附加什么条件?
case when 的用法给你举个例子
select case when payamount>100 then 100 else payamount end from table where id=123
如果payamount大于100 ,则取100,其余取原值。追问

select sum(PayAmount) from Table where ID=123,要在聚合函数中使用,所以sum(case when....then....else...end),括号里面的内容不会写

以上是关于case when用法sql的主要内容,如果未能解决你的问题,请参考以下文章

SQL中的decode及case when的用法

SQL语句中case,when,then的用法

case when用法

SQL语句中case,when,then的用法

MYSQL case when 的两种用法

SQL中case when then用法