簡體   English   中英

SQL:比較兩個不同表中的最大日期

[英]SQL: Comparing MAX Dates from Two different Tables

我有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

但是如何讓他們一起工作呢?

謝謝

嘗試這個:

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;

嘗試這個

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)

我認為這可以滿足您的需要( 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM