英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论