【问题标题】:SQL: two queries for different time periods, and calculate percentage change?SQL:两次查询不同时间段,并计算百分比变化?
【发布时间】:2016-06-25 16:45:57
【问题描述】:

我正在使用 BigQuery,并且有一个包含三列的表:district(字符串)、price(浮点数)和timestamp)。我的桌子是这样的:

district    price    date
OOX         200      2015-01-01
00Y         213      2015-01-01
00X         215      2015-01-01

我想计算 2005 年各区均价,2015 年各区均价,以及它们之间的百分比差异。换句话说,我想要如下所示的输出:

district   price_2005  price_2015  percent_change
00X        125         205         0.64
00Y        116         200         0.72

percent_change 列的格式并不重要 - 它也可以是百分比数字等。

如何使用 BigQuery 执行此操作?我已经走到这一步了:

SELECT district, AVG(price) AS price 
FROM mytable
WHERE date BETWEEN TIMESTAMP('2005-01-01') AND TIMESTAMP('2015-12-31')
GROUP BY district

但我不知道如何在不进行单独查询的情况下获取剩余的两列。我需要子查询吗?

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    您可以使用条件聚合来做到这一点。使用旧版 SQL 接口:

    select district,
           avg(case when year(date) = 2005 then price end) as price_2005,
           avg(case when year(date) = 2015 then price end) as price_2015,
           ((avg(case when year(date) = 2015 then price end) /
             avg(case when year(date) = 2005 then price end)
            ) - 1) as change
    from t
    group by district;
    

    更新后的SQL接口思路相同,但提取年份的功能不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多