0

I have two table_One and Table_Two for each client the very 1st Record goes into Table_One There after any more records for that client goes into Table_Two.
Now I want the Difference between the very last record and the 2nd last record added for that client. say X is the very last value added for the client and Y is the 2nd last value added for the client.
I want the Value X - Y = value in my result set.
I have attached a screen shot of the tables and desired result set.enter image description here


"Every Client will have a record in Table_One but may or may not have a record in Table_Two , Only the very 1st record goes into Table_One"
"If the very last two records are both in Table_Two then I need the Difference between them values."

my limitations are I cannot create a stored procedure as this query is being plugged into a 3rd party software and I can only execute ah-hoc sql there or UDFs but no stored procedures :(.

4

1 回答 1

1

first put all records in one result (using a cte)

then construct query by joining this to original table1, twice

with combined (clientid, date, column3) as
(select clientid, date, column3 from table1
 union all
select clientid, date, column3 from table2)
select t1.clientid, t1.column1, t1.column2, 
       l.column3-nl.column3   
from table1 t1
  join combined l  -- the last record
     on l.clientid = t1.clientid
       and l.date = (select max(date) 
                     from combined 
                     where clientid = t1.clientid)
  join combined nl -- the next to last record
     on nl.clientid = t1.clientid
       and nl.date = (select max(date) 
                     from combined 
                     where clientid = t1.clientid
                        and date < l.date)
于 2013-10-18T21:14:08.097 回答