简体   繁体   English

SQL Group By与派生表有关的问题

[英]SQL Group By issues with derived table

I'm attempting to create a table of all the latest payments made for an employee. 我正在尝试创建一张为雇员支付的所有最新付款的表格。 The original table has all the payments made to an employee since they started. 原始表包含了自雇员开始以来向雇员支付的所有款项。 I created a derived table to give me only the records with the latest date in them. 我创建了一个派生表,以便仅提供其中具有最新日期的记录。

I do still have some duplicates where the payment date is the same, in this case I want to add these payment together so they appear on one row instead. 我仍然有一些重复的付款日期相同的副本,在这种情况下,我想将这些付款加在一起,使它们出现在一行上。

Below is my working code; 下面是我的工作代码;

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)

This returns the below; 返回下面的内容;

在此处输入图片说明

I seem to have issues summing together p1, p2 & p3. 我似乎在汇总p1,p2和p3时遇到问题。 I think this because I am trying to use the GROUP BY function twice. 我想这是因为我试图两次使用GROUP BY函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM