Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将SQL中的数据转换为新列_Sql_Sql Server_Tsql_Group By_Pivot - Fatal编程技术网

将SQL中的数据转换为新列

将SQL中的数据转换为新列,sql,sql-server,tsql,group-by,pivot,Sql,Sql Server,Tsql,Group By,Pivot,我的数据如下: id maths phy chem 1 50 60 21 2 60 80 22 3 80 90 23 现在我希望它看起来像: sub 1 2 3 math 50 60 80 phy 60 80 90 chem 21 22 23 我的代码: select * from mrks pivot ( max(maths) for id in ([1], [2], [3]) ) piv 然而,我面

我的数据如下:

id maths phy chem 
1   50   60   21
2   60   80   22
3   80   90   23
现在我希望它看起来像:

sub   1   2   3
math 50  60  80 
phy  60  80  90
chem 21  22  23
我的代码:

select *
  from mrks
    pivot
(
  max(maths) 
  for id in ([1], [2], [3])
) piv
然而,我面临两个问题

  • 我无法转换化学值和物理值

  • 不能将数学、物理和化学分为以下几类:


  • 在SQL Server中,您可以使用
    交叉应用取消pivot,然后使用条件聚合进行透视:

    select 
        col,
        max(case when id = 1 then val end) col1,
        max(case when id = 2 then val end) col2,
        max(case when id = 3 then val end) col3
    from mytable t
    cross apply (values ('maths', maths), ('phy', phy), ('chem', chem)) p(col, val)
    group by col
    

    col | col1 | col2 | col3 :---- | ---: | ---: | ---: chem | 21 | 22 | 23 maths | 50 | 60 | 80 phy | 60 | 80 | 90 col | col1 | col2 | col3 :---- | ---: | ---: | ---: 化学| 21 | 22 | 23 数学| 50 | 60 | 80 phy | 60 | 80 | 90
    您不能在多个列上执行
    PIVOT
    ,您可以使用
    UNION
    实现所需的输出,如下所示

    SELECT 'Math' AS Sub,*
    FROM (SELECT id ,maths FROM mrks) t
    PIVOT(MAX(maths) FOR id IN ([1], [2], [3])) piv
    
    UNION ALL
    
    SELECT 'Phy' AS Sub,*
    FROM (SELECT id,phy FROM mrks) t
    PIVOT(MAX(phy) FOR id IN ([1], [2], [3])) piv
    
    UNION ALL
    
    SELECT 'Chem' AS Sub,*
    FROM (SELECT id,chem FROM mrks) t
    PIVOT(MAX(chem) FOR id IN ([1], [2], [3])) piv
    
    这也会起作用

    DECLARE @tble TABLE (id INT, maths INT, phy INT, chem INT)
    INSERT INTO @tble VALUES
    (1,50,60,21),(2,60,80,22),(3,80,90,23);
    
    select * from(
    SELECT ID,maths AS Scores, 'maths' as Subjects FROM @tble
    UNION
    SELECT ID,phy AS Scores, 'phy' as Subjects FROM @tble
    UNION
    SELECT ID,chem AS Scores, 'chem' as Subjects FROM @tble  
      ) s
    PIVOT
    (
      MIN(Scores) 
      FOR id IN ([1], [2], [3])
    ) piv
    

    如果有人插入行(4、75、77、81),您预计会发生什么?