1

我有 3 张桌子

用户

在此处输入图像描述

出席

在此处输入图像描述

支付

在此处输入图像描述

现在我喜欢得到

GroupID、用户名、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

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

谢谢

4

3 回答 3

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;
于 2012-11-01T17:15:31.210 回答
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)
于 2012-11-01T17:18:08.323 回答
0

我认为这可以满足您的需要(SqlFiddle 链接):

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
于 2012-11-01T17:26:46.557 回答