How to pivot rows into columns (custom pivoting)

前端 未结 6 1831
夕颜
夕颜 2020-11-27 05:27

I have a Sql Database table similar to the following:

Day   Period    Subject

Mon   1         Ch
Mon   2         Ph
Mon   3         Mth
Mon   4         CS
M         


        
6条回答
  •  青春惊慌失措
    2020-11-27 05:51

    Use cross apply to get all the values in a comma delimted format in a single column. instead of "7" different columns. The following query can be used for any column-> row mapping

    SELECT DISTINCT Day, [DerivedColumn] FROM  A CROSS APPLY ( SELECT Period + ',' FROM 
    B WHERE A.Day = B.Day Order By Period FOR XML PATH('') ) AS C (DerivedColumn)

    You will get [Ch,Ph,Mth,CS2,Lab1,Lab2,Lab3] in one column for Mon and so on ... You could use this as a table to query for any particular Day.

    Hope this helps

    提交回复
    热议问题