我尝试使用以下公式从子表创建新表:
create table if not exists `new_table` as
select * from (
select descrip,
max(case when ID = 1.01 then value else 0 end) 1.01
from(
select ID, `JUL-08` value, 1 descrip
from original_table
union all
select ID, `AGO-08` value, 2 descrip
from original_table
union all
select ID, `SET-08` value, 3 descrip
from original_table
union all
select ID, `OUT-08` value, 4 descrip
from original_table
union all
select ID, `NOV-08` value, 5 descrip
from original_table
union all
select ID, `DEZ-08` value, 6 descrip
from original_table
) src
group by descrip
) as `new_table`;
该公式运行良好,它创建了它要创建的表,但我想知道是否可以使用max函数为同一个表创建多个列,或者如果我必须为每个表重复整个公式ID可以创建一个新表,也可以在同一个公式中重复max()函数。
答案 0 :(得分:0)
您可以根据需要随时重复表达。你需要给他们不同的名字。
我还注意到表达式中有太多子查询:
create table if not exists `new_table` as
select descrip,
max(case when ID = 1.01 then value else 0 end) as `1.01`,
max(case when ID = 2.01 then value else 0 end) as `2.01`
from (select ID, `JUL-08` as value, 1 as descrip
from original_table
union all
select ID, `AGO-08` as value, 2 as descrip
from original_table
union all
select ID, `SET-08` as value, 3 as descrip
from original_table
union all
select ID, `OUT-08` as value, 4 as descrip
from original_table
union all
select ID, `NOV-08` as value, 5 as descrip
from original_table
union all
select ID, `DEZ-08` as value, 6 as descrip
from original_table
) src
group by descrip;
我不建议您将列命名为数字(或者就此而言的SQL关键字)。但是如果你这样做,你应该使用转义字符清楚你正在做什么。我会推荐更像id_1_01
的内容,因此不需要转义列名。