我使用SQL UNION ALL将多个表附加到一个表中。如何为新表分配名称?

huangapple go评论52阅读模式
英文:

I used SQL UNION ALL to append multiple tables in one table. How can I assign a name for the new table?

问题

I am a SQL beginner working on the Google Data Analytics Capstone project. There are 12 tables I need to analyze, with 13 columns and >5 million combined number of rows. I am running my queries in Google BigQuery and used the UNION ALL statement to append the tables in one new table. Now, I want to create a new column from the difference between column3 and column4. How can I do this without repeating the formula in the select statement of each of the 12 tables? Is there a way I can assign a name or a variable(?) for the new table so my code would look cleaner?

I tried creating a temporary table but it did not work and now I am stuck.

英文:

I am a SQL beginner working on the Google Data Analytics Capstone project. There are 12 tables I need to analyze, with 13 columns and >5 million combined number of rows. I am running my queries in Google BigQuery and used the UNION ALL statement to append the tables in one new table. Now, I want to create a new column from the difference between column3 and column4. How can I do this without repeating the formula in the select statement of each of the 12 tables? Is there a way I can assign a name or a variable(?) for the new table so my code would look cleaner?

I tried creating a temporary table but it did not work and now I am stuck.

答案1

得分: 1

你可以使用公用表表达式(CTE)来完成这个操作:

WITH MY_TABLE as (
    -- 在这里编写带有 UNION ALL 的查询
)
SELECT *, column3 - column4 AS new_col FROM MY_TABLE

但这不是一个实际的表格。你运行查询时,所有内部查询都将执行一次。

如果你想要一个真正的表格,我认为你可以创建一个类似这样的表格:

CREATE TABLE 新表格名 AS (
    -- 在这里编写带有 UNION ALL 的查询
)

然后像平常一样查询这个新表格。

英文:

You can use CTE for this:

WITH MY_TABLE as (
    -- you query with union alls
)
select *, column3-column4 new_col from MY_TABLE 

But this is not a table. All you r inner queries will be executed once you run it.

If you want real table, I believe you could create table something like this:

create table as (
    -- you query with union alls
)

and later query this new table as usual.

huangapple
  • 本文由 发表于 2023年4月1日 00:13:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定