SQL:比较两个不同表的MAX日期

时间:2012-11-01 17:01:08

标签: sql sql-server

我有3张桌子

用户

enter image description here

考勤

enter image description here

付款

enter image description here

现在我想得到

GroupID,UserName,MAX(PaymetDate),MAX(AttendenceDate)

MAX(PaymetDate)小于MAX(AttendenceDate)

这就是我试过的

    SELECT  MAX(PaymetDate) AS Paied_Upto
    FROM Payment
    Group by GroupID   

    SELECT  MAX(AttendenceDate) AS Last_ AttendenceDate
    FROM Attendence FULL OUTER JOIN Users ON Attendence.Username = Users.Username
    Group by Users.GroupID

但是如何让他们一起工作?

感谢

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT u.GroupID, u.UserName, py.LastPaymentDate, at.LastAttendenceDate
FROM User AS u,
(SELECT Username, Max(AttendenceDate) AS LastAttendenceDate FROM Attendence GROUP BY Username) AS at,
(SELECT GroupID, Max(PaymetDate) AS LastPaymentDate FROM Payment GROUP BY GroupID) AS py
WHERE u.UserName=at.Username
AND u.GroupID=py.GroupID
AND py.LastPaymentDate < at.LastAttendenceDate;

答案 1 :(得分:0)

试试这个

select p.GroupID, u.UserName, MAX(p.PaymetDate), MAX(a.AttendenceDate)
from dbo.Users u
inner join dbo.Attandence a
    ON u.UserName = a.UserName
Inner join dbo.Payment p
    ON u.groupID = p.GroupID
GROUP BY p.GroupID, u.UserName
Having MAX(p.PaymentDate) < MAX(a.attendenceDate)

答案 2 :(得分:0)

我认为这可以满足您的需求( SqlFiddle link ):

select UserName, GroupID, MaxAttendanceDate, MaxPaymentDate
from (
  select 
    u.UserName,
    u.GroupID,
    (select max(AttendanceDate) 
       from Attendance a 
       where a.UserName = u.UserName) as MaxAttendanceDate,
    (select max(PaymentDate) 
       from Payment p
       where p.GroupID = u.GroupId) as MaxPaymentDate
  from [User] u
) x
where MaxAttendanceDate > MaxPaymentDate