带舍入功能的Ratio_to_report

时间:2019-09-26 12:41:11

标签: google-bigquery

我正在尝试计算数据中每个值的贡献百分比,并且还需要总计(百分比)限制为2个小数点。

下面是我构建的代码:

count(rate(kube_pod_created[1h])) by(namespace)

如果我删除底数(即总数和百分比),我会得到结果,但不能将%限制为2个小数点

2 个答案:

答案 0 :(得分:0)

您可以拥有类似的内容:

SELECT *, purchases/total as percent
FROM (
    SELECT *, MAX(purchases) OVER(PARTITION BY test) total
    FROM t
    )
order by percent desc

答案 1 :(得分:0)

您似乎仍在使用旧版SQL-您可以在下面使用它来解决您的问题

#legacySQL
SELECT test, Total, ROUND(Percentage, 2) AS Percentage
FROM (
  SELECT test, 
    COUNT(*) AS Total, 
    RATIO_TO_REPORT(Total) OVER() AS Percentage
  FROM [project:dataset.abc_table]
  WHERE platform IN ('A', 'B', 'C', 'D')
  GROUP BY  test 
)
ORDER BY Percentage DESC    

同时,强烈推荐migrate to BigQuery Standard SQL-以下是制作方法

#standardSQL
SELECT DISTINCT test, 
  COUNT(1) OVER(PARTITION BY test) AS Total,
  ROUND(COUNT(1) OVER(PARTITION BY test) / COUNT(1) OVER(), 2) AS Percentage
FROM `project.dataset.abc_table`
WHERE platform IN ('A', 'B', 'C', 'D')
ORDER BY Percentage DESC