将两个查询与group by结合使用

时间:2018-04-05 07:09:19

标签: sql google-bigquery

假设我有一个包含列的表

event_name,
event_date,
event_key,
event_value

我对两个event_names review_meta_with_productreview_meta_click_purchase_product

感兴趣

对于两个event_names中的每一个,我想要每个(event_date, event_key, event_value)组的总计数。

我目前有两个关于两个event_names的查询,想知道它们是否可以合并。

(以下是BigQuery的查询,但我认为这个想法仍然适用于常规的SQL。)

   select event.date, event.name as event_name, event_param.value.string_value as review_meta_name, count(*) as ct from `com_zibann_littlehome_debugEug_ANDROID.app_events_20180403`,
       UNNEST(event_dim) as event,
       UNNEST(event.params) as event_param
   where DATE(TIMESTAMP_MICROS(event.timestamp_micros)) >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
       and event.name = 'review_meta_with_product'
   and event_param.key = "review_meta_name"
 group by event.date, event.name, event_param.key, event_param.value.string_value


 select event.date, event.name as event_name, event_param.value.string_value as review_meta_name, count(*) as ct from `com_zibann_littlehome_debugEug_ANDROID.app_events_20180403`,
       UNNEST(event_dim) as event,
       UNNEST(event.params) as event_param
   where DATE(TIMESTAMP_MICROS(event.timestamp_micros)) >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
       and event.name = 'review_meta_click_purchase_product'
   and event_param.key = "review_meta_name"
 group by event.date, event.name, event_param.key, event_param.value.string_value

1 个答案:

答案 0 :(得分:1)

是的,可以使用条件聚合组合这两个查询:

select event.date, event.name as event_name, 
       event_param.value.string_value as review_meta_name, 
       count(case 
                when event.name = 'review_meta_click_purchase_product' 
                   then 1 
             end) as ct_purchase,
       count(case 
                when event.name = 'review_meta_with_product' 
                   then 1 
             end) as ct_product 
from `com_zibann_littlehome_debugEug_ANDROID.app_events_20180403`,
      UNNEST(event_dim) as event,
      UNNEST(event.params) as event_param
where DATE(TIMESTAMP_MICROS(event.timestamp_micros)) >=
         DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
      and event.name IN ('review_meta_click_purchase_product', 'review_meta_with_product')
      and event_param.key = "review_meta_name"
group by event.date, 
         event.name, 
         event_param.key, 
         event_param.value.string_value