大查询中的问题。如何计算百分比?

时间:2018-07-12 13:02:11

标签: sql google-bigquery

SELECT count(time_stamp) AS Cnt,
       (CASE
            WHEN DATEDIFF(CURRENT_DATE(), time_stamp) < 30 THEN "This_month"
            WHEN DATEDIFF(CURRENT_DATE(), time_stamp) >= 30
                 AND DATEDIFF(CURRENT_DATE(), time_stamp) <= 60 THEN "Past_month"
            ELSE "rest"
        END) AS dateblock
FROM database90days
GROUP BY dateblock

现在我得到的结果是

Cnt      dateblock  
964      rest
1,035    Past_month
1,176    This_month

现在我需要检查从本月到上个月的百分比增加和百分比减少。请帮我在上面的查询中怎么做

2 个答案:

答案 0 :(得分:2)

您可以使用LAG()获得上一个计数。

SELECT datablock,
       (CASE WHEN DATEDIFF(CURRENT_DATE(), time_stamp) < 30 THEN 'This_month'
             WHEN DATEDIFF(CURRENT_DATE(), time_stamp) >= 30 AND
                  DATEDIFF(CURRENT_DATE(), time_stamp) <= 60 THEN 'Past_month'
             ELSE 'rest'
        END) AS dateblock
       COUNT(time_stamp) AS Cnt,
       LAG(COUNT(time_stamp)) OVER (PARTITION BY datablock ORDER BY MIN(time_stamp)) as prev_cnt
FROM database90days
GROUP BY dateblock;

其余只是这些值的算术运算。

答案 1 :(得分:0)

我不确定该解决方案是否正是您要寻找的,但是如果您打算使用3值结构(本月,上个月,其他时间),我相信这是一种解决方法:

SELECT 100*((This_month-Past_month)/Past_month) as change_ratio_in_percent,
      This_month,
      Past_month,
      BEginning
      FROM (
       SELECT (select count(*) FROM dataset WHERE DATE_DIFF(CURRENT_DATE(), time_stamp, DAY)< 30) AS This_month,
       (select count(*) FROM dataset WHERE DATE_DIFF(CURRENT_DATE(), time_stamp, DAY) >= 30 AND DATE_DIFF(CURRENT_DATE(), first_name, DAY) <= 60) AS Past_month,
       (select count(*) FROM dataset WHERE DATE_DIFF(CURRENT_DATE(), time_stamp, DAY) > 60) AS BEginning
FROM dataset)
GROUP BY change_ratio_in_percent, This_month, Past_month, BEginning;