sql - 在 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
但这给了我空值。
解决方案
假设没有可以定义行排序的属性 -
;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
推荐阅读
- asp.net-core - ASP.NET Core GraphQL:如何查询项目范围?
- javascript - 传销二叉树更新
- javascript - 添加下一个按钮以循环遍历javascript中的元素
- android - 回收站视图中的弹出窗口
- laravel - laravel 命名资源无法正常工作并从头开始删除点
- scala - 将两列的Dataframe转换为排序列表
- reactjs - 使用反应钩子的搜索过滤器(useEffect / useState)
- java - 从片段中包含的列表视图中获取第一个项目,Android Studio
- c++ - 为什么这里没有调用复制构造函数?
- gdal - EPSG-GDAL 转换