代码之家  ›  专栏  ›  技术社区  ›  Ben P

对不在GROUPBY中的字段使用if语句

  •  2
  • Ben P  · 技术社区  · 6 年前

    我试图建立一个表,每次访问我的网站都有一行,然后列显示 0 1 基于用户是否执行了某些操作。

    要构建这些列,我使用了if语句,但这样做意味着我必须将if语句中引用的字段添加到group by列表中,这又意味着我现在每次访问都有多行,如下所示:

    enter image description here

    如何调整代码,使每行只有一行 visit_ref ,显示该会话中的所有交互?

    这是我的代码:

    SELECT CONCAT(CAST(fullVisitorId AS STRING),CAST(visitId AS STRING)) AS visit_ref,
    customDimension.value AS UserID,
    # Event actions
    IF(hits.eventInfo.eventAction LIKE "Basket Icon Click",1,0) AS basket_icon_click,
    IF(hits.eventInfo.eventAction LIKE "Add to Basket PLP",1,0) AS basket_add_plp,
    # Event labels
    IF(hits.eventInfo.eventLabel LIKE "Close Mini Basket",1,0) AS closed_minibasket_click,
    IF(hits.eventInfo.eventLabel LIKE "%Delivery",1,0) AS checked_delivery_pdp,
    IF(hits.eventInfo.eventLabel LIKE "%Returns",1,0) AS checked_returns_pdp,
    # Page interactions
    IF(hits.page.pagepath LIKE "%/Account/SignIn%",1,0) AS sign_in,
    # Device category
    IF(device.deviceCategory LIKE "mobile",1,0) AS device_mobile,
    IF(device.deviceCategory LIKE "desktop",1,0) AS device_computer,
    IF(device.deviceCategory LIKE "tablet",1,0) AS device_tablet,
    
    IF(COUNT(DISTINCT hits.transaction.transactionid)>0,1,0) AS ordered
        FROM `PROJECT.DATASET.ga_sessions_20*` AS t
          CROSS JOIN UNNEST(hits) AS hits
          CROSS JOIN UNNEST(t.customdimensions) AS customDimension
        WHERE parse_date('%y%m%d', _table_suffix) between 
        DATE_sub(current_date(), interval 1 day) and
        DATE_sub(current_date(), interval 1 day)
        AND customDimension.index = 2
        GROUP BY visit_ref, UserID, device.deviceCategory, hits.eventInfo.eventAction, hits.eventInfo.eventCategory, hits.eventInfo.eventLabel, hits.page.pagepath, geoNetwork.country
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Gordon Linoff    6 年前

    使用条件聚合。…具有 case if() :

    SELECT CONCAT(CAST(fullVisitorId AS STRING), CAST(visitId AS STRING)) AS visit_ref,
            customDimension.value AS UserID,
    # Event actions
            max(case when hits.eventInfo.eventAction LIKE 'Basket Icon Click' then 1 else 0 end) AS basket_icon_click,
            max((case when hits.eventInfo.eventAction LIKE 'Add to Basket PLP' then 1 else 0 end) AS basket_add_plp,
            . . .
    from . . .
    group by visit_ref, user_id;