【发布时间】: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 天的值:
- 当月的值
- 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