遇到SQL间隔问题

时间:2019-06-20 15:03:34

标签: sql postgresql where-clause

我需要获取一年前某个特定日期的数据总和。但是我在间隔

上遇到了困难
?- distinct(person(P)).
P = joe ;
P = mary ;
P = bob.

这按预期工作,但我需要传递一个不使用Now()的日期

Select 0 - sum(l.icdetailquantity )
    from inventoryline l 
    where l.icmasterid = 'WAD185967E' and l.icdetailtranstype = 5 
        and l.icdetaildate <= '01-Jan-2019' and l.icdetaildate >  Now() - interval '1 year'

第二个SQl给出错误

Select 0 - sum(l.icdetailquantity )
    from inventoryline l 
    where l.icmasterid = 'WAD185967E' and l.icdetailtranstype = 5 
        and l.icdetaildate <= '01-Jan-2019' and l.icdetaildate >  '01-Jan-2019' - interval '1 year'

2 个答案:

答案 0 :(得分:2)

您正在尝试从字符串中减去年份。这不起作用,您必须首先使用以下命令将您的字符串转换为日期对象:

to_date(date_string,format)  

适合您的示例:

to_date('01-Jan-2019', 'DD-Mon-YYYY') - interval '1 year'

http://www.postgresqltutorial.com/postgresql-to_date/

答案 1 :(得分:1)

您尝试过

Select 0 - sum(l.icdetailquantity )
from inventoryline l 
where l.icmasterid = 'WAD185967E' 
  and l.icdetailtranstype = 5 
  and l.icdetaildate <= date '2019-01-01' 
  and l.icdetaildate >  date '2019-01-01' - interval '1 year'

根据我正在查看的文档(https://www.postgresql.org/docs/current/functions-datetime.html),似乎需要“ date”关键字。