【问题标题】:Selecting the Max Date From Multiple Tables从多个表中选择最大日期
【发布时间】:2013-03-05 01:43:42
【问题描述】:

任何帮助都会非常感激。我正在尝试从一组表中选择最后一个活动日期。这些表格包括输入日期、注释日期、付款日期和索赔日期。我想只返回所有这些日期的最大值。此外,我只想要超过 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)

【问题讨论】:

  • 您发布的查询有什么问题?
  • 哪种 SQL 方言? mySQL、Microsoft SQL、Oracle 等?

标签: sql max


【解决方案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

【讨论】:

  • 它是 Microsoft SQL。我正在从 SQL Server 2008 查询数据。我尝试了上面的代码,但它没有工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2014-01-24
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多