内部连接到我的复杂查询中的另一个表

时间:2017-08-09 17:32:52

标签: google-bigquery

我已经创建了一个静态表,我想加入此查询以添加到我的结果中。该表名为“平板电脑”。并包含字段:branch,tablet_id,imei和phone。

我希望在IMEI上匹配,并将branch,tablet_id和phone添加为结果列。但是,由于此查询的复杂性,我不明白该怎么做。

SELECT
  event_dim.date AS Date,
  (
  SELECT
    value.value.string_value
  FROM
    UNNEST(user_dim.user_properties)
  WHERE
    key = 'imei_id') AS IMEI,
  (
  SELECT
    value.value.string_value
  FROM
    UNNEST(user_dim.user_properties)
  WHERE
    key = 'division_id') AS Branch,
  (
  SELECT
    value.value.string_value
  FROM
    UNNEST(user_dim.user_properties)
  WHERE
    key = 'truck_id') AS Truck,
  (
  SELECT
    value.value.string_value
  FROM
    UNNEST(user_dim.user_properties)
  WHERE
    key = 'installer_id') AS Installer,
  COUNT(*) AS Count
FROM
  `smarttruck-6d137.com_usiinc_android_ANDROID.app_events_*`
CROSS JOIN
  UNNEST(event_dim) AS event_dim
WHERE
  event_dim.name = 'app_exception'
  AND EXISTS (
  SELECT
    1
  FROM
    UNNEST(event_dim.params)
  WHERE
    key = 'fatal'
    AND value.int_value = 1 )
  AND REGEXP_EXTRACT(_TABLE_SUFFIX, r'(\d+)') BETWEEN FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY))
  AND FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 0 DAY))
GROUP BY
  Date,
  IMEI,
  Branch,
  Truck,
  Installer
ORDER BY
  Date DESC,
  Count DESC;

1 个答案:

答案 0 :(得分:2)

假设你问题中的主要问题是正确的 - 尝试简单的LEFT JOIN你已经拥有的东西

  
#standardSQL
SELECT 
  date, main.IMEI, main.Branch, Truck, Installer, count,
  tablets.branch, tablet_id, phone
FROM (
  SELECT
    event_dim.date AS DATE,
    (SELECT value.value.string_value FROM UNNEST(user_dim.user_properties) WHERE key = 'imei_id') AS IMEI,
    (SELECT value.value.string_value FROM UNNEST(user_dim.user_properties) WHERE key = 'division_id') AS Branch,
    (SELECT value.value.string_value FROM UNNEST(user_dim.user_properties) WHERE key = 'truck_id') AS Truck,
    (SELECT value.value.string_value FROM UNNEST(user_dim.user_properties) WHERE key = 'installer_id') AS Installer,
    COUNT(*) AS COUNT
  FROM `smarttruck-6d137.com_usiinc_android_ANDROID.app_events_*`
  CROSS JOIN UNNEST(event_dim) AS event_dim
  WHERE event_dim.name = 'app_exception'
    AND EXISTS (SELECT 1 FROM UNNEST(event_dim.params) WHERE key = 'fatal' AND value.int_value = 1 )
    AND REGEXP_EXTRACT(_TABLE_SUFFIX, r'(\d+)') BETWEEN FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY))
    AND FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(), INTERVAL 0 DAY))
  GROUP BY DATE, IMEI, Branch, Truck, Installer
) main
LEFT JOIN `yourproject.yourdataset.tablets` AS tablets
ON tablets.imei = main.IMEI
ORDER BY date DESC, count DESC