SQL Server:对两行求和并创建一行,然后在病房之后删除重复项

时间:2018-10-28 15:54:35

标签: sql-server tsql

Empid   OrgID    UniqueRowID   YearMonth      s      e       seOrg
1517    754     201802-1517-754 201802       0,81   0,81    0,49
1517    754     201802-1517-754 201802        1        1    0,39

我要在重复行上方将一行总和(s)/ 2,总和(e)/ 2,总和(seorg)/ s

 1517   754     201802-1517-754 201802        .905   .905       .88

需要在行上方,并在计算出单行后删除两个重复项

2 个答案:

答案 0 :(得分:0)

使用avg和sum作为:

select Empid, OrgId, UniqueRowId, YearMonth, 
       avg(s) as s,avg(e) as e,sum(seOrg) as seorg
  from tab
group by Empid, OrgId, UniqueRowId, YearMonth;

答案 1 :(得分:0)

您可以使用通用表表达式通过两步过程来实现。
第一步是在cte中选择平均值和总和并更新表格,
第二步是使用row_number删除重复项:

BEGIN TRY
    BEGIN TRANSACTION

    WITH CTE AS
    (
        SELECT  Empid, OrgID, UniqueRowID, YearMonth,
                AVG(s) As avgS,
                AVG(e) As avgE,
                SUM(seOrg)  As sumSeOrg
        FROM TableName
        GROUP BY Empid, OrgID, UniqueRowID, YearMonth
    )

    UPDATE T
    SET s = avgS,
        e = avgE,
        seOrg = sumSeOrg
    FROM TableName T
    JOIN CTE 
        ON T.Empid = CTE.Empid
        AND T.OrgID = CTE.OrgID
        AND T.UniqueRowID = CTE.UniqueRowID 
        AND T.YearMonth = CTE.YearMonth;

    WITH CTE AS
    (
        SELECT  Empid, OrgID, UniqueRowID, YearMonth,
                -- order by is not important since all duplicates now have the same values
                ROW_NUMBER() OVER(PARTITION BY Empid, OrgID, UniqueRowID, YearMonth ORDER BY @@SPID) As RN
        FROM TableName
    )

    DELETE FROM CTE WHERE RN > 1

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION
END CATCH