添加额外的总工资行

时间:2018-10-31 09:58:11

标签: sql-server unpivot

salary表:

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
 Grand Total        21600

“”我喜欢在empcode'2'之后显示总计  总计”

我将总计代码写为

select SalaryCode, SalaryDetails from
(select ecode,BASIC,HRA,CONV,(BASIC+HRA+CONV)SUB_Total from empstb) a unpivot(SalaryDetails for SalaryCode in (ecode,BASIC,HRA,CONV,SUB_Total)) upvt

but i don't know how to add grand total to it

1 个答案:

答案 0 :(得分:1)

您可以结合使用取消透视和分组设置。不确定您将最终输出用于什么

DECLARE @Salary TABLE
(
    EmpCode INT NOT NULL,
    BasicSalary INT NOT NULL,
    HRA INT NOT NULL,
    Conv INT NOT NULL
)

INSERT INTO @Salary (EmpCode,BasicSalary,HRA,Conv)
VALUES (1,10000,500,300),(2,10000,500,300);

SELECT  CASE
        WHEN GROUPING(CA1.ColName) = 1 AND GROUPING(S.EmpCode) = 1 THEN 'GrandTotal' 
        WHEN GROUPING(CA1.ColName) = 1 THEN 'Total' 
        ELSE CA1.ColName
    END AS SalaryCode,
    SUM(CA1.ColVal) -   CASE --Adjust the sum to exclude the EmpCode values
                            WHEN GROUPING(CA1.ColName) = 1 AND GROUPING(S.EmpCode) = 1 THEN SUM(S.EmpCode) / 4
                            WHEN GROUPING(CA1.ColName) = 1 THEN S.EmpCode
                            ELSE 0
                        END AS SalaryDetails
FROM    @Salary AS S
CROSS
APPLY   (VALUES (CAST('BasicSalary' AS VARCHAR(50)),BasicSalary,2),('HRA',HRA,3),('Conv',Conv,4),('EmpCode',EmpCode,1)) AS CA1(ColName,ColVal,RowPos)
GROUP   BY GROUPING SETS((),(EmpCode),(EmpCode,ColName,CA1.RowPos))
ORDER   BY ISNULL(S.EmpCode,MAX(S.EmpCode) OVER ()+1), ISNULL(CA1.RowPos,MAX(CA1.RowPos) OVER()+1) ASC;

编辑

已根据OP调整了输出。确实感觉到此级别的演示不属于这里,但这应该是必需的。由于EmpCode已包含在列表中,因此必须进行一些调整以确保它不包含在总数中。此外,还添加了一个位置值以正确的顺序输出