Sql server 2005 如何获得存储过程结果集中第一列第一个值和第一列最后一个值之间的差值?
我正在获取以下查询的结果集Sql server 2005 如何获得存储过程结果集中第一列第一个值和第一列最后一个值之间的差值?,sql-server-2005,Sql Server 2005,我正在获取以下查询的结果集 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(
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 1AND 4 and year(S.invoicedate) BETWEEN 2009 AND 2010
GROUP BY
YEAR(S.invoicedate),Month(S.invoicedate)
ORDER BY
YEAR(S.invoicedate),Month(S.invoicedate)
现在我想知道结果集中第一列第一个值(即250)和第一列最后一个值(即238)的数量之间的差异
作为单独的列,即。只有一个值
可以吗?在查询中使用单独的表还是在同一个表中
问候,
NSJ以下是使用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
请注意,在CASE表达式中,如果不匹配WHEN子句,则结果为NULL。所以你的ELSE NULL部分是多余的。另外,在发布代码时,请突出显示代码,并使用问题文本框上方的{}按钮格式化代码
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
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,ROW_NUMBER() over (order by Year(invoicedate),Month(invoicedate)) as rn,
ROW_NUMBER() over (order by Year(invoicedate),Month(invoicedate)) as descrn into #temp
FROM SALESDATA S
where month(S.invoicedate) BETWEEN 1AND 4 and year(S.invoicedate) BETWEEN 2009 AND 2010
GROUP BY YEAR(S.invoicedate),Month(S.invoicedate)
ORDER BY YEAR(S.invoicedate),Month(S.invoicedate)
declare @diffAmt int = (select top 1 Qty from #temp where rn = 1) - (select top 1 Qty from #temp where descrn = 1)
select *,@diffAmt as DiffAmt from #temp