sql - Redshift 查询日期数据
问题描述
我正在尝试从 redshift 表中查询数据。
我有一个 users 表,其中包含name、age、gender和created_at等列,例如:
|----|-----|------|----------|
|name|age |gender|created_at|
------------------------------
|X | 24 | F | some_date|
______________________________
我需要查询上面的表格,这样我就有了额外的列,比如created_this_week、created_last_week、created_last_4_week、current_month、last_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 的新手,并且仍处于学习阶段,我花了过去几个小时试图自己做这件事,但没有成功。如果有人可以帮助我解决这个问题,我将不胜感激。
解决方案
你会使用一个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;
推荐阅读
- python - 下载 Dropbox 目录中最近添加的图像的脚本
- c - C:将字符串与“%.c”进行比较?
- java - TEstRestTemplate 在调试模式下返回内容,但在测试模式下返回空数组
- python - 在 Python 中从 XPath 抓取数据时使用通配符
- python - 在 bat 脚本中运行 python 脚本
- c# - 如何在 Xamarin Forms 中使用 ControlTemplate 进行替代绑定
- android - 片段或活动中的休息调用和 SQLite.NET
- python - 存储和保存多维数据集的最佳方法是什么
- reactjs - 使用 Dex 进行调试转换类导致 Windows 崩溃
- r - 在函数中使用省略号使用 tidy 原则读取数据