2013-03-05 82 views
0

任何幫助都將如此令人難以置信的讚賞。我試圖從一組表中選擇最後的活動日期。這些表格包括輸入日期,記錄日期,付款日期和索賠日期。我想只返回所有這些日期的最大值。此外,我只想記錄超過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) 
+0

什麼是您發佈與查詢問題? – 2013-03-05 01:45:56

+0

哪種SQL方言? mySQL,Microsoft SQL,Oracle等? – Sparky 2013-03-05 01:57:15

回答

0

我想,這可能會做這一切在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 
+0

這是Microsoft SQL。我正在查詢來自SQL Server 2008的數據。我嘗試了上面的代碼,但沒有成功。 – 2013-03-06 23:12:54

+0

@MichaelSigman。 。 。它是如何「不起作用」的? – 2013-03-06 23:13:37

相關問題