首页 > 解决方案 > 创建临时表,它复制一列的值但更改另一列的值

问题描述

我有 2 列的表 Z:

在此处输入图像描述

我需要再添加 2 种类型:C 和 D,其中 Total 值分别等于 A 和 B,并创建一个新的临时 X 表,如下所示: 在此处输入图像描述

我想使用 C 的总值等于 A 且 D 的总值等于 B 的逻辑,而不是使用 insert into 函数,在该函数中我将 C 的值声明为 12,将 D 的值声明为 15,因为原始 Total表 Z 的值将不断变化;因此,我不想每次都手动插入新值。我也无权在数据库中创建新表,因此表 Z 是从 select 语句派生的,我无法创建新的永久表。所以我希望创建一个表 Z 的临时表。

谢谢您的帮助!

标签: sqlrowstemp-tables

解决方案


一种方法使用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');

推荐阅读