sql - 如何在 SQL Server 中合并两条记录并对一列求和
问题描述
有一个包含两列的简单表。Col1 就像一个标识符。
我想对具有相同 Col1 值的行数求和。并更新当前表。
当前表:
Col1 | Quantity
-----+----------
12 | 3
15 | 7
12 | 2
我需要的UPDATED表是将 Col1=12 的两行的数量相加(例如 .. WHERE Col1=12 ...)并将它们合并为一行:
Col1 | Quantity
-----+----------
12 | 5
15 | 7
在 SQL Server 查询中怎么可能?
请注意,我需要更新表格。不只是选择行。
解决方案
使用sum()
聚合group by
with cte as
(
select col1,quantity,row_number() over(partition by col1 order by quantity) as rn
from tablename
)
update a set a.quantity=b.qty
from cte a
inner join
(select col1, sum(quantity) as qty
from tablename
group by col1
)b on a.col1=b.col1 where rn=1
delete a from tablename a
join
(
select col1,quantity,row_number() over(partition by col1 order by quantity) as rn
from tablename
)b on a.col1=b.col1 and rn>2
推荐阅读
- php - 关系在 Laravel Tinker 中有效,但不在控制器中
- reactjs - 反应本机 - FETCH - 授权标头不起作用
- jsf - adf addpartialTarget 未正确呈现 UI 组件
- c# - 如何通过函数传递类型并使用它来查找所有变量类型?
- roslyn - 如何使用 Roslyn 添加行尾注释
- python - coursera 网站的网页抓取在每次运行中都会产生不同的结果
- php - 如何解决 Codeigniter 3 中的 require 错误
- gnuplot - 如何在gnuplot 4.0中制作圆圈
- r - 基于三个规则合并数据
- report - URL 链接合并字段的 Apex Salesforce 页面参考