[英]How can I create a new column in a table to show only specific data from another column using SQL?
I am trying to figure out how to create a new column in a table that will be labelled as Release_Year and that will only show the year that each movie was released.我想弄清楚如何在表中创建一个新列,该列将被标记为 Release_Year,并且只会显示每部电影的发行年份。
I have not attempted to run a query as I do not know where to begin.我没有尝试运行查询,因为我不知道从哪里开始。
You need to add a new column of type int.您需要添加一个新的 int 类型的列。
ALTER TABLE `projectID.datasetID.movie_table`
ADD COLUMN Release_Year int64;
Then you need to fill the column with values, you can do this using a merge
statement.然后您需要用值填充该列,您可以使用
merge
语句来完成此操作。 We also use a group by to ensure we have unique mappings.我们还使用 group by 来确保我们拥有唯一的映射。
merge into `projectID.datasetID.movie_table` as target_table
using (
select
movie_title,
extract(year from release_date) as release_year
from
`projectID.datasetID.movie_table`
group by
movie_title,
release_year) as mapping
on
mapping.movie_title = target_table.movie_title
when matched
then
update set target_table.release_year = mapping.release_year
This is untested but the general idea should work.这是未经测试的,但总体思路应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.