Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在两列中选择月份_Sql_Postgresql - Fatal编程技术网

Sql 在两列中选择月份

Sql 在两列中选择月份,sql,postgresql,Sql,Postgresql,如何在两个不同的日期列中选择月份?我原来的桌子是这样的 id occured_at expire_at 1 2017-03-17 10:21:22.935278 2017-04-17 10:21:22.935278 2 2017-04-24 10:21:22.93851 3 2017-04-27 10:21:22.941801 2017-05-77 10:21:22.941801 4 2017-09-17 10:21:22.941801 20

如何在两个不同的日期列中选择月份?我原来的桌子是这样的

id occured_at                  expire_at
1  2017-03-17 10:21:22.935278  2017-04-17 10:21:22.935278
2  2017-04-24 10:21:22.93851   
3  2017-04-27 10:21:22.941801  2017-05-77 10:21:22.941801
4  2017-09-17 10:21:22.941801  2017-10-17 10:21:22.941801
我想选择2017-04年在发生的或在过期的,并将日期截断为年和月,结果如下

id occured_at                  expire_at
1  2017-03                     2017-04
2  2017-04   
3  2017-04                     2017-05
我是sql的新手。如果有人能帮忙,我们将不胜感激。

要显示您想要的日期,请使用
To_char()
。限制行数可以使用几种不同的方法:

使用date\u trunc:

select id, 
       to_char(occurred_at, 'yyyy-mm') as occurred_at,
       to_char(expire_at, 'yyyy-mm') as expire_at
from the_table
where date_trunc('month', occured_at) = date '2017-04-01'
   or date_trunc('month', expire_at) = date '2017-04-01';
也可以使用比较格式字符串:

select id, 
       to_char(occurred_at, 'yyyy-mm') as occurred_at,
       to_char(expire_at, 'yyyy-mm') as expire_at
from the_table
where to_char(occured_at, 'yyyy-mm') = '2017-04'
   or to_char(expire_at, 'yyyy-mm') = '2017-04';
也可以使用范围查询:

select id, 
       to_char(occurred_at, 'yyyy-mm') as occurred_at,
       to_char(expire_at, 'yyyy-mm') as expire_at
from the_table
where (   occured_at >= timestamp '2017-04-01 00:00:00' 
      and occured_at < timestamp '2017-05-01 00:00:00')
   or (   expire_at >= timestamp '2017-04-01 00:00:00' 
      and expire_at < timestamp '2017-05-01 00:00:00');
选择id,
将字符(发生于'yyyy-mm')改为发生于,
将字符(在'yyyy-mm'到期)作为
从桌子上
其中(发生时间>=时间戳'2017-04-01 00:00:00'
并在<时间戳'2017-05-01 00:00:00'发生
或(过期时间>=时间戳'2017-04-01 00:00:00'
并于<时间戳'2017-05-01 00:00:00'到期;

最后一个查询能够对这些列使用索引。对于前两个查询,您需要在使用的表达式上定义表达式索引。

首先确定您使用的是哪种RDBMS抱歉,我忘了删除
mysql
标记我尝试过的第一个解决方案,我有一个小问题,我将代码
SELECT id,date\trunc(发生时间,'yyyyy-mm')作为month,date trunc运行(expire_at,'yyyy-mm')作为expireMonth,从_表中,其中'2017-04-01'介于月份和expireMonth之间
。结果显示月份和expireMonth列不存在。因此,我的问题是我无法使用新列名称进行查询?或者我错过了somthing@Barry:这是一个已经被回答了很多次的不同问题: