简体   繁体   English

BigQuery:Select 列如果存在,否则输入 NULL?

[英]BigQuery: Select column if it exists, else put NULL?

I am updating a daily dashboard.我正在更新每日仪表板。 Assume everyday I have two tables TODAY and BEFORE_TODAY .假设我每天都有两个表TODAYBEFORE_TODAY What I have been doing daily was something like:我每天都在做的事情是这样的:

SELECT a, b FROM TODAY
UNION ALL
SELECT a,b FROM BEFORE_TODAY;

TODAY table is generated daily and is appended to all the data before it. TODAY表每天生成并附加到它之前的所有数据。 Now, I need to generate a new column say c and in order to UNION ALL the two, I need that to be available on BEFORE_TODAY as well.现在,我需要生成一个新列,比如c并且为了 UNION ALL 这两个,我需要它在BEFORE_TODAY也可用。

How can I add a conditional statement to BEFORE_TODAY to check if I have a c column and use that column, else use NULL instead of it.如何向BEFORE_TODAY添加条件语句以检查我是否有c列并使用该列,否则使用NULL代替它。

Something is wrong with your data model. You should be putting the data into separate partitions of the same table.您的数据 model 有问题。您应该将数据放入同一个表的不同分区中。 Then you would have no problems.那么你就没有问题了。 You could just query the master table for the partitions you want.您可以只查询主表以获得所需的分区。 The column would appear in the history, with a NULL value.该列将出现在历史记录中,其值为NULL

That is the right solution.这是正确的解决方案。 You can create a hacked solution, assuming that your tables have a primary key.您可以创建一个被黑的解决方案,假设您的表有一个主键。 For instance, if a, b is unique on each row, you could do:例如,如果a, b在每一行上都是唯一的,你可以这样做:

select t.a, t.b, t.c
from today t
union all
select b.a, b.b,
       (select c  -- not qualified on purpose
        from before_today b2
        where b2.a = b.a and b2.b = b.b
       ) as 
from before_today b cross join
     (select null as c) c;

If b.c does not exist, then the subquery returns c.c .如果b.c不存在,则子查询返回c.c If it does exist this it returns b2.c from the subquery.如果它确实存在,它会从子查询中返回b2.c

Although by combining dynamic SQL and INFORMATION_SCHEMA, you can write a script to achieve what you told, this doesn't seems to be the right thing to do.虽然通过结合动态 SQL 和 INFORMATION_SCHEMA,您可以编写一个脚本来实现您所说的,但这似乎不是正确的做法。

As part of your data model planning, you should add column c to BEFORE_TODAY ahead of time.作为数据 model 规划的一部分,您应该提前将列 c 添加到BEFORE_TODAY The newly added column on existing rows will always have NULL value.现有行上新添加的列将始终具有 NULL 值。 Then you can add column to TODAY and reference column c as normal.然后您可以将列添加到TODAY并照常引用列 c。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM