使用别名以避免重复计算代码

时间:2020-09-08 00:33:21

标签: google-bigquery

我正在创建报告视图,并且有很多“%”计算。有没有一种方法可以写一个计算,然后给它分配一个别名,以便可以再次重用...相对于每次都需要重写该值时都要重写计算?

SELECT 
Date,
COUNT(DISTINCT fullVisitorId) AS Users,
COUNT(DISTINCT CONCAT(fullVisitorId, CAST(visitStartTime AS STRING))) AS Sessions,
COUNT(CASE WHEN geoNetwork.country in("United States","Canada") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) as US_SESSIONS,
COUNT(CASE WHEN geoNetwork.country in("United Kingdom","Ireland") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) as UK_SESSIONS,
COUNT(CASE WHEN geoNetwork.country in("Australia","New Zealand") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) as AU_SESSIONS,
COUNT(CASE WHEN geoNetwork.country in("United States","Canada") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) / COUNT(DISTINCT CONCAT(fullVisitorId, CAST(visitStartTime AS STRING))) as US_percent,
COUNT(CASE WHEN geoNetwork.country in("United Kingdom","Ireland") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) / COUNT(DISTINCT CONCAT(fullVisitorId, CAST(visitStartTime AS STRING))) as UK_percent,
COUNT(CASE WHEN geoNetwork.country in("Australia","New Zealand") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) / COUNT(DISTINCT CONCAT(fullVisitorId, CAST(visitStartTime AS STRING))) as AU_percent
FROM `TABLE*` 
group by Date

最好是类似

SELECT 
Date,
COUNT(DISTINCT fullVisitorId) AS Users,
COUNT(DISTINCT CONCAT(fullVisitorId, CAST(visitStartTime AS STRING))) AS Sessions,
COUNT(CASE WHEN geoNetwork.country in("United States","Canada") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) as US_SESSIONS,
COUNT(CASE WHEN geoNetwork.country in("United Kingdom","Ireland") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) as UK_SESSIONS,
COUNT(CASE WHEN geoNetwork.country in("Australia","New Zealand") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) as AU_SESSIONS,
COUNT(CASE WHEN geoNetwork.country in("United States","Canada") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) / Sessions as US_percent,
COUNT(CASE WHEN geoNetwork.country in("United Kingdom","Ireland") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) / Sessions as UK_percent,
COUNT(CASE WHEN geoNetwork.country in("Australia","New Zealand") THEN CONCAT(fullVisitorId, CAST(visitStartTime AS STRING)) ELSE NULL END) / Sessions as AU_percent
FROM `TABLE*` 
group by Date

0 个答案:

没有答案