sql - 创建临时表,它复制一列的值但更改另一列的值
问题描述
我有 2 列的表 Z:
我需要再添加 2 种类型:C 和 D,其中 Total 值分别等于 A 和 B,并创建一个新的临时 X 表,如下所示:
我想使用 C 的总值等于 A 且 D 的总值等于 B 的逻辑,而不是使用 insert into 函数,在该函数中我将 C 的值声明为 12,将 D 的值声明为 15,因为原始 Total表 Z 的值将不断变化;因此,我不想每次都手动插入新值。我也无权在数据库中创建新表,因此表 Z 是从 select 语句派生的,我无法创建新的永久表。所以我希望创建一个表 Z 的临时表。
谢谢您的帮助!
解决方案
一种方法使用union all
. 我不确定是否需要聚合,但这会计算所有 As 和 B 的总数:
insert into x (type, total)
select 'C', sum(total)
from x
where type = 'A'
union all
select 'D', sum(total)
from x
where type = 'B';
或者,如果不需要聚合,则case
表达式允许对数据进行单次扫描:
insert into x (type, total)
select (case when type = 'A' then 'C' else 'D' end), total
from x
where type in ('A', 'B');
推荐阅读
- javascript - 如何使用 Jest 对需要 cookie 的函数进行单元测试?
- javascript - 如何删除某些类型的元素是 js?
- php - 无法使 dump() 在 Symfony 4.2 工具栏中工作
- javascript - coturn + webrtc:NAT后面的主机无法连接到服务器
- c++ - 使用 std::extent 获取数组的第二维
- java - Java循环棋盘标记
- java - Android X:错误膨胀类 android.support.design.widget.FloatingActionButton - android
- spring - spring boot @Value("${somevalue}") 注解是如何工作的?
- firebase - 使用 Firebase 身份验证在 Flutter 中注销用户不起作用
- javascript - ClickAwayListener 的回调函数在执行中途停止