我试图创建一张包含为员工支付的所有最新款项的表格。原始表格包括自员工开始以来向员工支付的所有款项。我创建了一个派生表,只给我带有最新日期的记录。
我仍然有一些重复的付款日期是相同的,在这种情况下,我想将这些付款一起添加,以便它们显示在一行上。
以下是我的工作代码;
SELECT T1.EmployeeCode
, T2.Staff_Number
, T2.Firstname + ' ' + T2.Surname AS Name
, T1.PaymentDate
, T1.p1
, T1.p2
, T1.p3
FROM DB1.dbo.PARTIFPSNI AS T1
--This section is supposed to return only the latest date
INNER JOIN (
SELECT EmployeeCode, MAX(PaymentDate) as MaxDate
FROM DB1.dbo.PARTIFPSNI
GROUP BY EmployeeCode
) T1A ON T1.EmployeeCode = T1A.EmployeeCode and T1.PaymentDate = T1A.MaxDate
LEFT JOIN DB2.dbo.Personnel_Records AS T2 ON (T1.EmployeeCode = T2.Staff_Number)
返回以下内容;
我似乎有问题汇总p1,p2& P3。我想这是因为我试图使用GROUP BY函数两次。
答案 0 :(得分:2)
SELECT T1.EmployeeCode ,
T2.Staff_Number ,
T2.Firstname + ' ' + T2.Surname AS Name ,
T1.PaymentDate ,
SUM(T1.p1) ,
SUM(T1.p2) ,
SUM(T1.p3)
FROM DB1.dbo.PARTIFPSNI AS T1
INNER JOIN ( SELECT EmployeeCode ,
MAX(PaymentDate) AS MaxDate
FROM DB1.dbo.PARTIFPSNI
GROUP BY EmployeeCode
) T1A ON T1.EmployeeCode = T1A.EmployeeCode
AND T1.PaymentDate = T1A.MaxDate
LEFT JOIN DB2.dbo.Personnel_Records AS T2 ON ( T1.EmployeeCode = T2.Staff_Number )
GROUP BY T1.EmployeeCode ,
T2.Staff_Number ,
T2.Firstname + ' ' + T2.Surname ,
T1.PaymentDate