SUM DATA SELECT - 具有相同ID的2个人

时间:2012-12-11 10:02:32

标签: sql sql-server tsql

我的查询显示两个名字为“Anna”,“Szymkowiak”和同样“id”的人,但这是同一个人。我怎么能总结这个?例如:id“80”,“Anna”,“Szymkowiak”,“23”,2 - > 23是月20加3的总和,2是Aneks 1加1的总和

SELECT DISTINCT SBA.HRSystemId AS Id, SBA.FirstName,  SBA.Surname, 
    CASE WHEN SBA.EndDate < GETDATE() 
    THEN DATEDIFF(MONTH,SBA.StartDate,SBA.EndDate)
    ELSE DATEDIFF(MONTH,SBA.StartDate, GETDATE()) 
    END AS Miesiace_Przepracowane,
    MAX(SBC.ContractNumber) AS Aneks
    FROM SB_Applications SBA JOIN SB_Contracts SBC ON SBA.ApplicationId = SBC.ApplicationId 
    WHERE SBA.IsActiveYN = 1 AND SBA.HRSystemId != 0 AND SBC.ApplicationStatusId = 4
    GROUP BY SBA.FirstName, SBA.Surname,SBA.StartDate,SBA.EndDate,SBA.StartDate,SBA.HRSystemId,SBC.ContractNumber;

我得到了这个:

id |FirstName|Surname|Miesiace_Przepracowane|Aneks
80, Anna, Szymkowiak, 20, 1
80, Anna, Szymkowiak, 3, 1
91, Jack, Sparrow, 2, 1
92, Tom, Jones, 1, 1
100, Rocky, Balboa, 3, 0

此示例不起作用 enter image description here

感谢各位同事的帮助,这对我来说是非常好的训练:)我给了你一点帮助。

2 个答案:

答案 0 :(得分:1)

当你已经拥有GROUP BY时,你几乎不想使用DISTINCT;这是无关紧要的 最自然,最快捷的方法是使用派生表扩展查询:

SELECT HRSystemId, FirstName, SurName,
       Sum(Miesiace_Przepracowane) Miesiace_Przepracowane,
       MAX(Aneks) Aneks
FROM
(
    SELECT SBA.HRSystemId AS Id, SBA.FirstName,  SBA.Surname, 
        CASE WHEN SBA.EndDate < GETDATE() 
        THEN DATEDIFF(MONTH,SBA.StartDate,SBA.EndDate)
        ELSE DATEDIFF(MONTH,SBA.StartDate, GETDATE()) 
        END AS Miesiace_Przepracowane,
        MAX(SBC.ContractNumber) AS Aneks
        FROM SB_Applications SBA JOIN SB_Contracts SBC ON SBA.ApplicationId = SBC.ApplicationId 
        WHERE SBA.IsActiveYN = 1 AND SBA.HRSystemId != 0 AND SBC.ApplicationStatusId = 4
        GROUP BY SBA.FirstName, SBA.Surname,SBA.StartDate,SBA.EndDate,SBA.StartDate,SBA.HRSystemId,SBC.ContractNumber
) X
GROUP BY HRSystemId, FirstName, SurName;

答案 1 :(得分:1)

Select ID,FirstName,Surname,SUM(Miesiace_Przepracowane) as Miesiace_Przepracowane,SUM(Aneks) as Aneks from
(
SELECT DISTINCT SBA.HRSystemId AS Id, SBA.FirstName,  SBA.Surname, 
    CASE WHEN SBA.EndDate < GETDATE() 
    THEN DATEDIFF(MONTH,SBA.StartDate,SBA.EndDate)
    ELSE DATEDIFF(MONTH,SBA.StartDate, GETDATE()) 
    END AS Miesiace_Przepracowane,
    MAX(SBC.ContractNumber) AS Aneks
    FROM SB_Applications SBA JOIN SB_Contracts SBC ON SBA.ApplicationId = SBC.ApplicationId 
    WHERE SBA.IsActiveYN = 1 AND SBA.HRSystemId != 0 AND SBC.ApplicationStatusId = 4
    GROUP BY SBA.FirstName, SBA.Surname,SBA.StartDate,SBA.EndDate,SBA.StartDate,SBA.HRSystemId,SBC.ContractNumber;
) a
Group by  ID,FirstName,Surname