Bigquery如何动态设置查询

时间:2016-07-18 17:15:41

标签: google-bigquery

在下面的查询中,我得到产品名称,产品中每个项目的数量以及购买产品的每个客户的数量,然后计算购买产品的客户的百分比。我很难编码总独特客户的价值。我想知道如何在我的查询中动态合并它。根据购买日期加入是我想到的唯一解决方案。有没有其他有效的方法来实现这一目标?
查询以下

(SELECT ProdName, COUNT(ProdName) AS No_of_Prods, 
EXACT_COUNT_DISTINCT(cust) as No_of_cust, 
(EXACT_COUNT_DISTINCT(cust)/1500)*100 as Percentage_of_cust 
FROM 
  [Prod-cust] 
WHERE 
  (STRFTIME_UTC_USEC(Timestamp,"%Y%m%d")) = (STRFTIME_UTC_USEC(DATE_ADD(CURRENT_TIMESTAMP(), -1, "day"), "%Y%m%d")) 
GROUP BY 
  1,
ORDER BY 
  2 DESC)

enter image description here 查询总独特客户如下

(SELECT EXACT_COUNT_DISTINCT(cust), 
FROM 
  [Prod-cust]
WHERE 
  (STRFTIME_UTC_USEC(Timestamp,"%Y%m%d")) = (STRFTIME_UTC_USEC(DATE_ADD(CURRENT_TIMESTAMP(), -1, "day"), "%Y%m%d")) 

2 个答案:

答案 0 :(得分:1)

SELECT 
    one.ProdName AS ProdName, 
    one.No_of_Prods AS No_of_Prods, 
    one.No_of_cust AS No_of_cust, 
    (one.No_of_cust/all.No_of_cust)*100 AS Percentage_of_cust 
FROM (
  SELECT 
    ProdName, 
    COUNT(ProdName) AS No_of_Prods, 
    EXACT_COUNT_DISTINCT(cust) AS No_of_cust
  FROM [Prod-cust] 
  WHERE 
    (STRFTIME_UTC_USEC(TIMESTAMP,"%Y%m%d")) = (STRFTIME_UTC_USEC(DATE_ADD(CURRENT_TIMESTAMP(), -1, "day"), "%Y%m%d")) 
  GROUP BY 1
) AS one
CROSS JOIN (
  SELECT EXACT_COUNT_DISTINCT(cust) AS No_of_cust, 
  FROM [Prod-cust] 
  WHERE 
    (STRFTIME_UTC_USEC(TIMESTAMP,"%Y%m%d")) = (STRFTIME_UTC_USEC(DATE_ADD(CURRENT_TIMESTAMP(), -1, "day"), "%Y%m%d")
) AS all

答案 1 :(得分:0)

SELECT number, RATIO_TO_REPORT(number) OVER() ratio
FROM (SELECT 10 number),(SELECT 40 number),(SELECT 70 number),(SELECT 20 number),(SELECT 30 number)

RATIO_TO_REPORT会添加所有数字,并为您提供number/(sum number)的比率。

更新:如果我们需要计算DISTINCT客户的数量,那么COUNT_DISTINCT()OVER()将作为子查询:

SELECT number, number/distincts ratio
FROM (
  SELECT number, COUNT_DISTINCT(id) OVER() distincts 
  FROM (SELECT 10 number, 1 id),(SELECT 30 number, 2 id),
       (SELECT 60 number, 3 id),(SELECT 20 number, 1 id),
       (SELECT 40 number, 1 id)
)