Выбор максимальной даты из нескольких таблиц

любая помощь будет так невероятно оценена. Я пытаюсь выбрать дату последней активности из группы таблиц. Таблицы включают дату входа, дату примечания, дату платежа и дату требования. Я хотел бы вернуть только максимальное значение из всех этих дат. Кроме того, мне нужны только записи, в которых не было активности более 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
Это Microsoft SQL. Я запрашиваю данные с SQL Server 2008. Я попробовал приведенный выше код, и он не сработал. - person Michael Sigman; 07.03.2013