在日期之间获取数据

时间:2014-06-02 03:21:44

标签: sql postgresql

我有查询来获取数据cost_month / month,如下所示:

select sum(xscf_cost_month) as cost_month
from ncloud_data_service_cof a
join ncloud_data_ba b on b.xcba_cof_no = a.xscf_cof_no
where to_time('2014-05', 'YYYY-mm') between to_char(b.xcba_activation_date, 'YYYY-mm') and to_char(b.xcba_end_activation_date, 'YYYY-mm')
上面的

查询显示错误: “错误:运算符不存在:日期> =文本 第4行:to_date('2014-05','YYYY-mm')在to_char之间(b.xcba_a ...“

如何解决?我尝试使用to_time更改to_char,但没有得到解决方案。 请帮帮我..

2 个答案:

答案 0 :(得分:0)

你打算这个吗?

select sum(xscf_cost_month) as cost_month
from ncloud_data_service_cof a join
     ncloud_data_ba b
     on b.xcba_cof_no = a.xscf_cof_no
where '2014-05' between to_char(b.xcba_activation_date, 'YYYY-mm') and 
                        to_char(b.xcba_end_activation_date, 'YYYY-mm');

您无需转换字符串'2014-05'。它已经是一个字符串。

答案 1 :(得分:0)

这个仍然可以使用列b.xcba_activation_date和b.xcba_end_activation_date上的索引:

SELECT sum(xscf_cost_month) as cost_month
FROM ncloud_data_service_cof a 
     JOIN
         ncloud_data_ba b ON b.xcba_cof_no = a.xscf_cof_no
WHERE to_time('2014-05', 'YYYY-mm') BETWEEN date_trunc('month', b.xcba_activation_date) AND date_trunc('month', b.xcba_end_activation_date);