如何区分第一列第一个值和第一列存储过程结果集中的最后一个值?

时间:2011-01-28 08:26:59

标签: 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(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

现在我希望结果集中第一列QTY的第一个值(即250)和第一列的最后一个值(即238)

as Separate column。(即只有单个值)。

是否可以?(使用单独的表或在查询中的同一表中)

此致

NSJ

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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