繁体   English   中英

BigQuery使用where子句过滤表中并不总是存在的列

[英]BigQuery use the where clause to filter on a column that not always exists in the table

我需要为多个表创建某种统一查询。 一些表包含具有类型的特定列。 如果是这种情况,我需要对其应用过滤。 我不知道该怎么做。

我有两个表

table_customer_1

CustomerId, CustomerType
1, 1
2, 1
3, 2

Table_customer_2

Customerid
4
5
6

该查询必须类似于下面的查询,并且对两个表都适用(表名将被使用该查询的客户替换):

    With input1 as(
        SELECT
        (CASE WHEN exists(customerType) THEN customerType ELSE "0" END) as customerType, *
    FROM table_customer_1)
    SELECT * from input1
WHERE customerType != 2

以下是BigQuery标准SQL

#standardSQL
SELECT *
FROM `project.dataset.table` t
WHERE SAFE_CAST(IFNULL(JSON_EXTRACT_SCALAR(TO_JSON_STRING(t), '$.CustomerType'), '0') AS INT64) != 2  

或为简化起见,您可以忽略强制转换为INT64并使用与STRING的比较

#standardSQL
SELECT *
FROM `project.dataset.table` t
WHERE IFNULL(JSON_EXTRACT_SCALAR(TO_JSON_STRING(t), '$.CustomerType'), '0') != '2'  

以上将适用于您放置的任何表而不是project.dataset.tableproject.dataset.table_customer_1project.dataset.table_customer_2我认为这很通用

我认为这样做没有充分的理由。 但是,可以通过使用子查询的作用域规则来实现:

SELECT t.*
FROM (SELECT t.*,
             (SELECT customerType  -- will choose from tt if available, otherwise x
              FROM table_customer_1 tt
              WHERE tt.Customerid = t.Customerid
             ) as customerType
      FROM (SELECT t.* EXCEPT (Customerid)
            FROM table_customer_1 t
           ) t CROSS JOIN
           (SELECT 0 as customerType) x
     ) t
WHERE customerType <> 2

暂无
暂无

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

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