• 数据库实现动态表头



    适用行:主要适用于表头的不确定性 比如专家评分时 未评的专家不显示在表头中

    关键点:数据库的列转行


    下面开始实现:

    1:建表

    CREATE  TABLE Student
    (
        student_id int PRIMARY KEY IDENTITY(1,1),
        student_name varchar(20) NOT NULL    
    )
    
    CREATE TABLE Teacher
    (
        teacher_id int PRIMARY KEY IDENTITY(1,1),
        teacher_name varchar(20) NOT NULL
    )
    
    CREATE TABLE Marks
    (
        student_id int FOREIGN KEY REFERENCES Student(student_id) ON UPDATE CASCADE ON DELETE CASCADE,
        teacher_id int FOREIGN KEY REFERENCES Teacher(teacher_id) ON UPDATE CASCADE ON DELETE CASCADE,
        PRIMARY KEY(student_id,teacher_id),
        mark int NOT NULL
    )

    2:插入数据

    INSERT INTO Student VALUES('李鹏')
    INSERT INTO Student VALUES('张三')
    INSERT INTO Student VALUES('小四')
    
    INSERT INTO Teacher VALUES('李老师')
    INSERT INTO Teacher VALUES('王老师')
    INSERT INTO Teacher VALUES('邓老师')
    INSERT INTO Teacher VALUES('不该出现的老师')
    
    INSERT INTO Marks VALUES(1,1,10)
    INSERT INTO Marks VALUES(1,2,20)
    INSERT INTO Marks VALUES(1,3,30)
    INSERT INTO Marks VALUES(2,1,40)
    INSERT INTO Marks VALUES(2,2,50)
    INSERT INTO Marks VALUES(3,3,60)

    3:动态表查询语句

    DECLARE @sql varchar(2000)
    
    SET @sql = 'SELECT student_name AS [姓名]'
    
    SELECT @sql = @sql + ',MAX(CASE teacher_id WHEN ''' + cast(A.teacher_id as nvarchar(5)) + ''' THEN mark ELSE NULL END ) AS [ ' + teacher_name + ' 评分]'
    FROM (SELECT DISTINCT teacher_id FROM Marks ) as A INNER JOIN Teacher ON Teacher.teacher_id = A.teacher_id
    
    SET @sql = @sql + ' FROM Marks INNER JOIN Student ON  Marks.student_id = Student.student_id GROUP BY student_name'
    exec(@sql) 
    print @sql

    4:遇到的错误以及处理方法

    ①:一定要注意 该有空格的地方必须有空格,该有逗号的地方有逗号

    ②:下列错误是因为 A.teacher_id是  int 类型的如果没有转化为nvarchar类型

    image

  • 相关阅读:
    poj 1523 SPF (无向图 的 割点)
    codeforces Walking in the Rain (dp 水题 线性 dp)
    GaleShapley算法
    hdu 1087 Super Jumping! Jumping! Jumping! (最大 上升子序列 线性 dp)
    poj 3694 Network (无向图的 割边 lca )
    codeforces To Add or Not to Add (排序 + 优化)
    hdu 3996 Gold Mine ( 最大权闭合图 )
    转:WINFORM多线程编程
    C#串口serialPort操作
    用C# 根据 JSC100 V5.0读写器通讯协议 编写读卡器API
  • 原文地址:https://www.cnblogs.com/lipeng0824/p/4373717.html
Copyright © 2020-2023  润新知