代码之家  ›  专栏  ›  技术社区  ›  Masoud

SQL Server中多列的透视

  •  1
  • Masoud  · 技术社区  · 6 年前

    我有三个方面:

    Melt, HSM, LSM
    

    在某些地区生产的每个订单都有以下数据:

    Start Date, Finish Date, Weight
    

    我有一个 View 在里面 SQL Server 2012 (上图),如何使用tsql创建生成下图的轴? enter image description here

    1 回复  |  直到 6 年前
        1
  •  2
  •   Masoud    6 年前

    可以使用条件聚合:

    SELECT [Order],
        MAX(CASE WHEN Area = 'Melt' THEN StartDate   END) AS Melt_SDate,
        MAX(CASE WHEN Area = 'Melt' THEN FinisthDate END) AS Melt_FDate,
        MAX(CASE WHEN Area = 'Melt' THEN Weight      END) AS Melt_Weight,
    
        MAX(CASE WHEN Area = 'HSM' THEN StartDate    END) AS HSM_SDate,
        MAX(CASE WHEN Area = 'HSM' THEN FinisthDa    END) AS HSM_FDate,
        MAX(CASE WHEN Area = 'HSM' THEN Weight       END) AS HSM_Weight,
    
        MAX(CASE WHEN Area = 'LSM' THEN StartDate    END) AS LSM_SDate,
        MAX(CASE WHEN Area = 'LSM' THEN FinisthDate  END) AS LSM_FDate,
        MAX(CASE WHEN Area = 'LSM' THEN Weight       END) AS LSM_Weight
    FROM tab_name
    GROUP BY [Order];   -- ORDER is reserved word, you should avoid such identifiers;
    

    为了让它更简洁,你可以使用 IIF :

    MAX(CASE WHEN Area = 'Melt' THEN StartDate   END) AS Melt_SDate,
    <=>
    MAX(IIF(Area='Melt',StartDate,NULL)) AS Melt_SDate,