【问题标题】:Getting values for 2 seperate dates in a month aggregated SQL table获取一个月聚合 SQL 表中 2 个不同日期的值
【发布时间】:2022-11-14 07:15:09
【问题描述】:

我有我的 SQL 表,它显示每个月,作为用户分配给一堆的值,如下所示:

+------------+-----------+---------+
|   month    |  userid   |  value  |
+------------+-----------+---------+
| 2022-09-01 | 394225402 | $129.26 |
| 2022-10-01 | 775891632 | $66.14  |
| 2022-09-01 | 823610245 | $652.87 |
| 2021-11-01 | 792204840 | $242.95 |
| 2022-05-01 | 783958351 | $525.10 |
| 2021-11-01 | 384623798 | $217.72 |
| 2022-10-01 | 487986883 | $338.19 |
| 2022-09-01 | 146730175 | $622.58 |
| 2022-11-01 | 834720939 | $332.03 |
| 2022-01-01 | 845336053 | $929.16 |
...

我想查询我的表以获取用户列表以及 2 天的值:

  1. 当月的值
  2. 6 个月前的值 得到一张这样的桌子
    +-----------+-------------------+-------------------+
    |  userid   | currentMonthValue | sixMonthsAgoValue |
    +-----------+-------------------+-------------------+
    | 394225402 | $525.10           | $45.18            |
    | 384623798 | $652.87           | $647.89           |
    | 845336053 | $234.84           | $9.49             |
    | 792204840 | $23.17            | $545.11           |
    +-----------+-------------------+-------------------+
    

    我希望它会像使用案例陈述一样简单,例如

    select
       userid,
       case when month = date_trunc(current_date(), month) THEN value ELSE NULL END currentMonthValue,
       case when month = date_sub(date_trunc(current_date(), month), interval 6 month) THEN value ELSE NULL END sixMonthsAgoValue
    from
       table
    

    但是,这并没有像我希望的那样为每个用户 ID 返回一个条目,而是每个用户 ID 每个月返回一个条目。

    有没有一种简单的方法来修改我的查询以提供我需要的内容?

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    你似乎想要currentMonthValuesixMonthsAgoValue 每个userid。如果是这样,请考虑使用如下聚合。

    select userid,
           max(case when month = date_trunc(current_date(), month) then value end) currentMonthValue,
           max(case when month = date_sub(date_trunc(current_date(), month), interval 6 month) then value end) sixMonthsAgoValue
      from `table`
     group by 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 2011-10-31
      • 1970-01-01
      相关资源
      最近更新 更多