sql CASE函数用法、利用CASE函数行转列

一,CASE写法

CASE函数格式:

    case [字段]

      when 表达式 then 显示数据

      when 表达式 then 显示数据

      else 显示数据

    end

举例:如图我们stud 表中studentNo字段有1,2,3,我们想用1代表男,2代表女来区分性别

执行的sql如下:

SELECT case StudentNo
 when '1' then ''  --1代表男
 when '2' then ''  --2代表女
 else '外星人'       --除开1和2,其他都是外星人
end as '性别',StudentName from stud

执行结果:

二,利用CASE函数行转列

建立演示数据:

CREATE  TABLE [StudentScores]
(
   [UserName]         NVARCHAR(20),        --学生姓名
    [Subject]          NVARCHAR(30),        --科目
    [Score]            FLOAT,               --成绩
)
 
INSERT INTO [StudentScores] SELECT 'Nick', '语文', 80
 
INSERT INTO [StudentScores] SELECT 'Nick', '数学', 90
 
INSERT INTO [StudentScores] SELECT 'Nick', '英语', 70
 
INSERT INTO [StudentScores] SELECT 'Nick', '生物', 85
 
INSERT INTO [StudentScores] SELECT 'Kent', '语文', 80
 
INSERT INTO [StudentScores] SELECT 'Kent', '数学', 90
 
INSERT INTO [StudentScores] SELECT 'Kent', '英语', 70
 
INSERT INTO [StudentScores] SELECT 'Kent', '生物', 85

建立好表和插入数据后我们看到的数据是这样的

如果我想知道每位学生的每科成绩,而且每个学生的全部成绩排成一行,这样方便我查看、统计,导出数据,执行如下sql

select UserName,
MAX(case subject when '语文' then Score else '0'  end ) as '语文', 
MAX(case subject when '数学' then Score else '0' end ) as '数学', MAX(case subject when '英语' then Score else '0' end ) as '英语', MAX(case subject when '生物' then Score else '0' end ) as '生物' from StudentScores group by UserName

执行结果:

 

 

参考地址:https://www.cnblogs.com/kerrycode/archive/2010/07/28/1786547.html

posted @ 2022-02-18 15:30  听见你的声音、潇  阅读(530)  评论(0编辑  收藏  举报