sql - Select record if exist in one table, else select from another -


i'm writing report quotes. quote table have copy track change history, every time change quote table old values salved in history table.

i want include field in report named original due date, show original due date quote. if there record in history table, should first due date there. otherwise should due date original table.

here sample of records have in tables.

table 1:

|id | order  | due date   | |1  | c1234  | 15/01/2000 | |2  | c1235  | 15/02/2000 | |3  | c1236  | 15/03/2000 | |4  | c1237  | 15/04/2000 | 

history table:

|id | order  | due date   | |1  | c1234  | 02/01/2000 | |2  | c1234  | 05/01/2000 | |3  | c1236  | 05/03/2000 | |4  | c1236  | 07/03/2000 | 

expected results:

|id | order  | original due date   | |1  | c1234  | 02/01/2000          | |2  | c1235  | 15/02/2000          | |3  | c1236  | 05/03/2000          | |4  | c1237  | 15/04/2000          | 

this code i've tried, not work because subquery return more 1 value.

 select case when exists (select 1 quoteheader qh inner join quoteheaderhistory qhh on qh.qh_recordid = qhh.qh_recordid)         (select qhh.qh_rfq_date quoteheader qh inner join quoteheaderhistory qhh on qh.qh_recordid = qhh.qh_recordid)         else qh.qh_rfq_date         end,     * quoteheader qh inner join quoteheaderhistory qhh           on qh.qh_recordid = qhh.qh_recordid 

this should work:

declare @tblo table(id int,[order] varchar(10),duedate date); insert @tblo values(1,'c1234','20000115'),(2,'c1235','20000215'),(3,'c1236','20000315'),(4,'c1237','20000415');  declare @tblh table(id int,[order] varchar(10),duedate date); insert @tblh values(1,'c1234','20000102'),(2,'c1234','20000105'),(3,'c1236','20000305'),(4,'c1236','20000307');  minhistoricaldates (     select min(duedate) minhistdat,[order]     @tblh     group [order] ) select orig.id        ,orig.[order]       ,isnull(mhd.minhistdat,orig.duedate) duedateresolved  @tblo orig left join minhistoricaldates mhd on mhd.[order]=orig.[order] 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -