sql - 如何将重复的行更新为一行
问题描述
我需要合并相同的条目并逐个数量行汇总数量。例如:
glass type height width quantity
---------------------------------------
4DC 1500 600 1
4DC 1500 600 2
4DC 1200 500 5
4DC 1200 500 2
3DC 1500 600 2
将会:
glass type height width quantity
---------------------------------------
4DC 1500 600 3
4DC 1200 500 7
3DC 1500 600 2
但我不想要任何选择查询,我需要更新表并删除重复的行并用总和更新其中一个。
我该怎么做?
解决方案
我的建议是更换表格:
select glasstype, height, width, sum(quantity) as quantity
into temp_t
from t
group by glasstype, height, width;
truncate table t; -- backup first!
insert into temp_t (glasstype, height, width, quantity)
select glasstype, height, width, quantity
from temp_t;
drop table temp_t;
或者,您可以分两步执行此操作:
with toupdate as (
select t.*, sum(quantity) over (partition by glasstype, height, width) as new_quantity
from t
)
update toupdate
set quantity = new_quantity;
with todelete as (
select t.*,
row_number() over (partition by glasstype, height, width order by glasstype) as seqnum
from t
)
delete from todelete
where seqnum > 1;
推荐阅读
- spring - 如何在带有 Scala 的注释中将 Spring 表达式语言用于数组
- android - 创建特价商品布局
- javascript - Neopixel / WS2811 通过本地 HTML 控制
- batch-file - Schtasks CMD .bat 麻烦
- c++ - 为 c++ st3 创建变量语法高亮
- csv - 如何在 tensorflow 2.0 中定义嵌入列?
- c# - Win10 .NET 3.5 RSACryptoServiceProvider.Dispose 引发 CryptographicException(访问被拒绝或共享违规)
- apache-spark - Pyspark 数据框列计算
- r - 基于条件滞后的变异
- java - JAVA_HOME 变量问题