Вот пример кода, который делает то, что вы хотите, используя cte.
declare @T table (id int identity, value int)
insert into @T values (10)
insert into @T values (20)
insert into @T values (30)
;with cte(id, value)
as (select id, value from @T)
select
id,
value,
(select top 1 value
from cte
order by id desc) -
(select top 1 value
from cte
order by id asc) as Diff
from cte
Вот ваш запрос с использованием cte.Это совсем не проверено, так как у меня нет ваших таблиц или данных.
with cte(qty, year1, mnth)
as
(select
cast(sum(case
when s.taxableamt <=2000
then (s.invoiceqty)
else null end) as decimal(30,2)) as qty ,
year(s.invoicedate) year1,
month(s.invoicedate) mnth
from
salesdata s
where
month(s.invoicedate) between 1 and 4 and
year(s.invoicedate) between 2009 and 2010
group by
year(s.invoicedate),
month(s.invoicedate)
)
select
qty,
year1,
mnth,
(select top 1 qty from cte order by year1, mnth desc) -
(select top 1 qty from cte order by year1, mnth asc) as diff
from cte
order by year1, mnth