Denormalizing Data (Maybe A Pivot?)

后端 未结 3 747
梦如初夏
梦如初夏 2020-12-19 18:10

I have a simple table containing Student Numbers and corresponding Teacher Numbers, and I need to denormalize it for input to a legacy system.

For example, here\'s

相关标签:
3条回答
  • 2020-12-19 18:37

    The old school method is to use CASE expressions; since SQL Server 2005 you can use PIVOT.

    CASE example:

    SELECT t.studnumber,
           CASE WHEN t.teachernumber = 57315 THEN t.teachernumber ELSE NULL END AS TEACHER1,
           CASE WHEN t.teachernumber = 88115 THEN t.teachernumber ELSE NULL END AS TEACHER1
    

    But dynamically placing a given teachernumber as teacher1/etc is an entirely different matter.

    0 讨论(0)
  • 2020-12-19 18:44

    I second PIVOT.

    Here are two interesting links with programmatic solutions to dynamic crosstab data in SQL.

    http://www.simple-talk.com/sql/t-sql-programming/creating-cross-tab-queries-and-pivot-tables-in-sql/

    http://www.simple-talk.com/sql/t-sql-programming/crosstab-pivot-table-workbench/

    0 讨论(0)
  • 2020-12-19 19:04

    You can use pivot. You also need to "Rank" your teachers 1-6. See my comment on how you want to do this. For now:

    Select StudNumber, TeacherNumber, TeacherRank
    from (
       Select ST.StudNumber
           , ST.TeacherNumber
           , ROW_NUMBER() OVER (PARTITION BY ST.StudNumber 
                        ORDER BY ST.TeacherNumber) AS TeacherRank
       From StudentTeacher AS ST)
    Where TeacherRank <=6
    

    Then you can pivot on this statement. Here is a good explanation: Using Pivot and UnPivot

    0 讨论(0)
提交回复
热议问题