zoukankan      html  css  js  c++  java
  • sql中case when then使用实例

    TABLE [Test] (
    [id] [int] IDENTITY (1, 1) NOT NULL ,
    [name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [subject] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
    [Source] [numeric](18, 0) NULL 
    ) ON [PRIMARY]
    GO
    INSERT INTO [test] ([name],[subject],[Source]) values (N'张三',N'语文',60)
    INSERT INTO [test] ([name],[subject],[Source]) values (N'李四',N'数学',70)
    INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'英语',80)
    INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'数学',75)
    INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'语文',57)
    INSERT INTO [test] ([name],[subject],[Source]) values (N'李四',N'语文',80)
    INSERT INTO [test] ([name],[subject],[Source]) values (N'张三',N'英语',100)
    Go
    
    
    select * from dbo.test
    --交叉表语句的实现:
    --1.用于:交叉表的列数是确定的
    select name,
    sum(case subject when '数学' then source else 0 end) as '数学',
    sum(case subject when '英语' then source else 0 end) as '英语',
    sum(case subject when '语文' then source else 0 end) as '语文' 
    from test 
    group by name
    
    --2.用于:交叉表的列数是不确定的
    declare @sql varchar(8000)
    
    set @sql = 'select name,'
    select @sql = @sql + 'sum(case subject when '''+subject+''' 
    then source else 0 end) as '''+subject+''','
    from (select distinct subject from test) as a 
    select @sql = left(@sql,len(@sql)-1) + ' from test group by name'
    exec(@sql)
    go
    
    
    --3.用于:交叉表的列数是不确定的
    declare @sql varchar(8000)
    set @sql = 'select id,name,'
    select @sql = @sql + '(case subject when '''+subject+''' 
    then source else null end) as '''+subject+''','
    from (select distinct subject from test) as a 
    select @sql = left(@sql,len(@sql)-1) + ' from test ' 
    exec(@sql)
    go
     
    
    
  • 相关阅读:
    如何解决列表框控件宽度不够的问题
    在windows Forms程序里面实现文件上传
    TFS的一些信息
    百钱百鸡问题
    如何移动SQL SERVER的系统数据库
    数据分页技术
    如何在报表中直接使用数据库中存储的图片
    重新注册MSJetOledb 4.0引擎
    2007 Microsoft Office Servers 已知问题/自述文件
    使用For XML与XSL(XSLT)配套快速输出查询结果到Web页面
  • 原文地址:https://www.cnblogs.com/kevin2013/p/1769688.html
Copyright © 2011-2022 走看看