table_One
Table_Two
very 1st Record goes into Table_One
之后,我为每个客户提供了两个any more records for that client goes into Table_Two
和Difference between the very last record and the 2nd last record
。
现在我希望为该客户端添加X
。说Y
是为客户添加的最后一个值,X - Y = value in my result set
是为客户添加的第二个最后一个值。
我想要值{{1}}。
我附上了表格和所需结果集的屏幕截图。
“每个客户都会在Table_One中有一条记录但在Table_Two中可能有也可能没有记录,只有第一条记录进入Table_One”
“如果最后两个记录都在Table_Two中,那么我需要它们之间的差值。”
我的限制是我无法创建存储过程,因为此查询被插入第三方软件,我只能在那里执行ah-hoc sql或UDF但没有存储过程:(。
答案 0 :(得分:1)
首先将所有记录放在一个结果中(使用cte)
然后通过将其连接到原始table1,两次
来构造查询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)