2011-01-28 42 views
0

我得到的结果集为以下查询如何获取第一列第一个值和第一个列之间的差异存储过程的结果集中的最后一个值?

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) 

QTY  MONTH/YEAR 
250   01/2010 
238   02/2010 
450   03/2010 
238   04/2010 
150   05/2010 
238   05/2010 
650   06/2010 
238   07/2010 
250   08/2010 
238   09/2010 
250   10/2010 
238   11/2010 
250   12/2010 
238   01/2009 
250   01/2009 
238   02/2009 
450   03/2009 
238   04/2009 

现在我想(ie238)第一列的第一个值的数量(ie250)和第一列尾值之间的差异结果集

as separate column。(ie only single value)。

这可能吗?(带独立的表或查询同一个表内)

问候,

NSJ

+0

未来的只是注意 - 在`CASE`表达,如果没有'WHEN`子句匹配,则结果为NULL。所以你的`ELSE NULL`部分是多余的。 – 2011-01-28 09:06:12

回答

0

下面是示例代码,你想要做什么用的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 
0
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 
相关问题