首页 > 解决方案 > Redshift 查询日期数据

问题描述

我正在尝试从 redshift 表中查询数据。

我有一个 users 表,其中包含nameagegendercreated_at等列,例如:

|----|-----|------|----------|
|name|age  |gender|created_at|
------------------------------
|X   | 24  | F    | some_date|
______________________________

我需要查询上面的表格,这样我就有了额外的列,比如created_this_weekcreated_last_weekcreated_last_4_weekcurrent_monthlast_month等 对于数据来自上周、本周、当前等条件的附加标志列应该是“Y”月,上个月,过去 4 周(不包括本周),所以从上周开始的最后 4 周等,如下所示。

|----|-----|------|-----------|------------|---------|-----------|------------|---------|
|name|age  |gender|created_at |current_week|last_week|last_4_week|current_mnth|last_mnth|
_________________________________________________________________________________________
| X  | 24  |  F   |CURRENTDATE|      Y     |   N     |     N     |    Y       |   N     |
_________________________________________________________________________________________
| F  | 21  |  M   | lst_wk_dt |      N     |   Y     |     Y     | Depends    | depends |
_________________________________________________________________________________________

我是 PostgresSQL 和 Redshift 的新手,并且仍处于学习阶段,我花了过去几个小时试图自己做这件事,但没有成功。如果有人可以帮助我解决这个问题,我将不胜感激。

标签: sqlamazon-redshift

解决方案


你会使用一个case表达式:

select t.*,
       (case when created_at >= now() - interval '1 week' then 'Y' else 'N' end) as week1,
       (case when created_at >= now() - interval '4 week' then 'Y' else 'N' end) as week4,
       . . .
from t;

推荐阅读