首页 > 解决方案 > 在 SQL Server 2008 中使用 case 语句减去 2 行

问题描述

我的数据如下所示,它在一个表中

Column1   Column2
abc       100
abc       200

现在我需要像下面

abc 100 //here 200-100

我正在努力实现这一目标。

我尝试使用 row_number ,然后使用 case 语句减去

Select
  column1,
  sum(
    case when rownum=1
    then column2
    end
    -
    case when rownum=2
    then column2
    end
  )
from table
group by column1

但这给了我空值。

标签: sqlsql-serversql-server-2008

解决方案


假设没有可以定义行排序的属性 -

;with cte as(
    select
        row_number() over (order by (select null)) as IndexId,
        Column1,
        Column2
    from @xyz
)
select sum(case when IndexID=1 then (-1 * Column2) else Column2 end), Column1
from cte
group by Column1

输入数据-

declare @xyz table(Column1   varchar(10),Column2 int)
insert into @xyz
select 'abc'       ,100 union all
select 'abc'       ,200

推荐阅读