使用 pivot 将行更改为列以使用 sql 对数据进行排序

Use pivot to change rows to columns for sequencing data using sql

我在一个视图中有数据,其中 Col_Head 列值应该是列 headers(它们对于 1-8 的每个数据序列都是常量。

并且 Value 列条目需要作为行值出现。

我需要写一些 SQL Col_Head 中的 transposes/pivots 行作为列 headers。

示例:

预期数据:

如果每个人都有一个特定的 ID,那么无论如何都不需要创建 CTE

首先,我通过 CTE 为每个人创建特定的 Id:

   /*Create CTE*/
    With tempTable as
    (
    select  
     row_number() over( order by(select 0) ) row_num,
    *
    from myTable
    ),newTable as(
    
    select 
    case when (row_num %8)>0 then (row_num /8)+1 else (row_num /8) end sp_Id,
    *
    from tempTable 
    )  

  /*MainQuery*/  
    select 
    *
    from (select sp_id, Col_Header,[Value] from newTable )as temp 
    pivot
    (
    max([Value])
    for Col_Header in ([Emp name],[Emp Dept],[Emp Grade],[Emp class],[Emp Sal],[Emp manager],[Emp Date of join],[Emp documents])
    ) pivotTable