zoukankan      html  css  js  c++  java
  • Sql Server 行转列 学员分数 例子

    if(EXISTS( SELECT * FROM sysobjects
      WHERE ID = OBJECT_ID('student')))
        drop table student

    create table student
    (
        stuid char(10) not null,
        stuname varchar(50) not null
    )

    insert into student values('050614001','张三')
    insert into student values('050614002','李四')
    insert into student values('050614003','王二')
    insert into student values('050614004','黑六')


    if(EXISTS( SELECT * FROM sysobjects
      WHERE ID = OBJECT_ID('subject')))
      drop table subject
    create table subject
    (
      sid int not null,
      sname varchar(50) not null
    )
    insert into subject values(1,'语文')
    insert into subject values(2,'数学')
    insert into subject values(3,'英语')
    insert into subject values(4,'物理')
    insert into subject values(5,'化学')



    if(EXISTS( SELECT * FROM sysobjects
      WHERE ID = OBJECT_ID('score')))
      drop table score
    create table score
    (
      stuid char(10) not null,
      sid int not null,
      score int not null
    )
    insert into score values('050614001',1,87)
    insert into score values('050614001',2,89)
    insert into score values('050614001',3,90)
    insert into score values('050614002',5,70)
    insert into score values('050614002',1,91)
    insert into score values('050614002',2,92)
    insert into score values('050614004',3,93)
    insert into score values('050614003',1,94)
    insert into score values('050614003',2,95)
    insert into score values('050614003',3,86)


    declare @strSQL  varchar(8000)

    SET @strSQL = 'select student.stuName [姓名]'
    select @strSQL = @strSQL + ',SUM(CASE subject.SNAME WHEN ''' + SNAME + ''' THEN score.[Score] END) [' + SNAME + ']' FROM (SELECT SNAME FROM [Subject]) AS tmp

    set @strSQL = @strSQL + ',sum(score) as 总分  from student
        left join score on student.stuId = score.stuid
        left join subject on score.sid = subject.sid
    GROUP BY student.STUID, student.STUNAME
    order by 总分 desc'

    exec (@strSQl)

    SQL SERVER 2005 中,已经有实现此功能的内置方法了。

  • 相关阅读:
    [Python学习之路] 猜大小游戏
    C语言学生成绩管理系统(简易版)
    malloc动态分配字符串数组“ 一个月内的提醒”
    结构体指针排序
    C语言结构体排序
    数据测压,数据库查询,修改,添加
    badboy脚本录制
    性能测试
    JDK开发环境搭建及环境变量配置(win10)Jmeter之安装和配置
    Charles 修改返回值response(方法 breakpoints)
  • 原文地址:https://www.cnblogs.com/yuanxianlai/p/2294630.html
Copyright © 2011-2022 走看看