1

我的查询显示两个名为“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

这个例子不起作用 在此处输入图像描述

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

4

2 回答 2

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;
于 2012-12-11T10:07:35.133 回答
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  
于 2012-12-11T10:08:42.757 回答