การเลือกวันที่สูงสุดจากหลายตาราง

ความช่วยเหลือใด ๆ จะได้รับการชื่นชมอย่างไม่น่าเชื่อ ฉันกำลังพยายามเลือกวันที่ของกิจกรรมสุดท้ายจากกลุ่มตาราง ตารางประกอบด้วยวันที่เข้า วันที่จดบันทึก วันที่ชำระเงิน และวันที่เรียกร้อง ฉันต้องการส่งคืนเฉพาะค่าสูงสุดจากวันที่เหล่านี้ทั้งหมด นอกจากนี้ ฉันต้องการบันทึกเฉพาะที่ไม่มีกิจกรรมใดๆ เกิน 45 วันเท่านั้น ขณะนี้ฉันกำลังใช้ SQL ต่อไปนี้เพื่อนำวันที่ทั้งหมดมาใช้ จากนั้นใช้เขตข้อมูลจากการคำนวณใน EXCEL เพื่อหาส่วนที่เหลือ เป็นไปได้ไหมที่จะทำทั้งหมดนี้ด้วย SQL?

ขอบคุณล่วงหน้า.

SELECT xrxTrnLgr.PatId, xrxTrnLgr.Balance, 
       Max(xrxPatNotes.NoteDate) AS 'Max of NoteDate', 
       Max(xrxTrnIcf.PostDate) AS 'Max of IcfPostDate', 
       Max(xrxPat.EntryDate) AS 'Entry Date', 
       Max(xrxPat.Coverage) AS 'Coverage', 
       Max(xrxTrnPay.PostDate) AS 'Last Payment'
  FROM  xrxTrnLgr 
  LEFT OUTER JOIN xrxPatNotes ON xrxTrnLgr.PatId = xrxPatNotes.PatId
  LEFT OUTER JOIN  xrxTrnIcf ON xrxTrnLgr.PatId = xrxTrnIcf.PatId
  LEFT OUTER JOIN xrxPat ON xrxTrnLgr.PatId = xrxPat.PatId
  LEFT OUTER JOIN xrxTrnPay ON xrxTrnLgr.PatId = xrxTrnPay.PatId
  GROUP BY xrxTrnLgr.PatId, xrxTrnLgr.Balance
  HAVING (xrxTrnLgr.Balance>$.01)

person Michael Sigman    schedule 05.03.2013    source แหล่งที่มา
comment
คำถามที่คุณโพสต์มีปัญหาอะไร   -  person Mahmoud Gamal    schedule 05.03.2013
comment
ภาษา SQL ใด mySQL, Microsoft SQL, Oracle และอื่นๆ   -  person Sparky    schedule 05.03.2013


คำตอบ (1)


ฉันคิดว่านี่อาจทำได้ทั้งหมดใน SQL:

select t.patid, t.balance,
       max(case when which = 'note' then thedate end) as note,
       max(case when which = 'post' then thedate end) as post,
       max(case when which = 'entry' then thedate end) as entry,
       max(case when which = 'coverage' then thedate end) as coverage,
       max(case when which = 'lastPayment' then thedate end) as lastPayment
from xrxTrnLgr t left join
     ((select patid, notedate as thedate, 'note' as which
       from xrxPatNotes
      ) union all
      (select patid, postdate, 'post'
       from xrxtrnIcf
      ) union all
      (select patid, EntryDate, 'entry'
       from xrxPat
      ) union all
      (select paid, Coverage, 'coverage'
       from xrxPat.Coverage
      ) union all
      (select patid, PostDate, 'LastPayment'
       from xrxTrnPay.PostDate
      ) 
    ) d
    on t.patid = d.patid
group by t.patid, t.balance
having min(now() - thedate) >= 45
person Gordon Linoff    schedule 05.03.2013
comment
มันคือไมโครซอฟต์ SQL ฉันกำลังสืบค้นข้อมูลจากเซิร์ฟเวอร์ SQL 2008 ฉันลองใช้โค้ดด้านบนแล้ว แต่ก็ไม่ได้ผล - person Michael Sigman; 07.03.2013