BigQuery: Matching tables through column and replacing value in other column in CASE statement

Viewed 68

I have two tables where some of the unique_ids in table v match the ones in table a. If field 'type' in table a has the value "standard_room" then I want to use the value of the 'datetime' field in table v but for all other values of field 'type' I want to stick with the value of the 'datetime' field in table a. I made sure that each unique_id in a row with type "standard_room" in table a has a matching unique_id in table v. So this is not the issue.

What I'm getting is a bunch of "standard_room" rows where the 'datetime' is NULL. I don't understand, it should at least fall back onto the ELSE condition and give me a.datetime instead. How can there be NULL? Maybe I need to use some kind of join?

As explained expected/desired output would be all rows from table a, but rows where type = "standard_room" should have the v.datetime value instead and the connection between the two is the unique_id column.

Please see my query below:

# Bigquery Standard SQL

WITH
  v AS (
    SELECT
      unique_id,
      `datetime`
    FROM
      `project.occupancy.v`
    WHERE `date` >= "2022-09-01"})
(SELECT
    CASE
      WHEN a.type = "standard_room" THEN ( SELECT DATETIME_TRUNC(`datetime`, HOUR) FROM v WHERE a.unique_id = v.unique_id)
    ELSE
    DATETIME_TRUNC(a.`datetime`, HOUR)
  END
    AS hour)
FROM
  `project.rooms.a` a,
  UNNEST(a.nested_field) nested_field
WHERE
  a.type != "suite"
  AND a.type != "apartment1"
  AND nested_field.k IN ("1346")
  AND nested_field.v NOT IN (7323,
    7360,
    7357,
    7354,
    7332))
0 Answers
Related