我需要像下面一样构造表,使用数据透视表或取消透视图动态地

时间:2018-10-31 05:07:38

标签: sql dynamic pivot unpivot

EmpSalary表:

EmpCode BASIC   HRA  CONV
--------------------------
   1    10000   500  300
   2    10000   500  300

所需的输出:

   SalaryCode   SalaryDetails
    EmpCode           1
    BASIC           10000
    HRA               500
    CONV              300
   Total            10800

    EmpCode           2
    BASIC           10000
    HRA               500
    CONV              300
   Total            10800

1 个答案:

答案 0 :(得分:0)

实际上,我们需要您使用的DBMS

以下包含unpivot子句的代码适用于Sql-ServerOracle

select SalaryCode, SalaryDetails
  from   
   (select EmpCode, BASIC,HRA,CONV,
           (BASIC+HRA+CONV) sub_Total  
      from EmpSalary 
      ) p  
unpivot  
   (SalaryDetails for SalaryCode in
      (EmpCode,BASIC,HRA,CONV,sub_Total)  
) unpvt;

Rextester Demo