尝试按日期过滤SQL结果

时间:2017-12-10 03:58:47

标签: sql postgresql

我有一个库的数据库,我正在尝试编写一个查询来返回所有尚未检出五年的书籍

它应该产生这样的东西......

 isbn |        title        |    author     
------+---------------------+---------------
  222 | The Art of the Deal | Trump
  444 | Im a cool guy       | Forrest Stone
(2 rows)

我有一个books表,

library6=# SELECT * FROM books;
 isbn |                 title                 |    author     
------+---------------------------------------+---------------
  111 | Harry Potter and the Sorcerer’s Stone | JK Rowlings
  222 | The Art of the Deal                   | Trump
  333 | to catch a crook                      | Robert Muller
  444 | Im a cool guy                         | Forrest Stone
  555 | rich i am                             | Bill Gates
(5 rows)

我有一个transactions表,

library6=# SELECT * FROM transactions;
 id | checked_out_date | checked_in_date | user_id | isbn 
----+------------------+-----------------+---------+------
  1 | 2016-01-01       | 2016-02-01      |       1 |  111
  2 | 2016-02-02       | 2016-03-02      |       2 |  111
  3 | 2016-03-03       | 2016-05-03      |       3 |  111
  5 | 2017-11-29       | 2017-12-04      |       5 |  555
  6 | 2017-11-28       | 2017-12-05      |       1 |  333
  4 | 2017-12-06       | 2017-12-09      |       4 |  111
  5 | 2010-01-01       | 2010-01-02      |       1 |  222
(7 rows)

到目前为止,我已经尝试过,它正确加入了两个表并返回了从未检出过的书,但却错过了5年前检查过的书。

library6=# SELECT b.title,b.author , b.isbn FROM transactions t
RIGHT OUTER JOIN books b ON t.isbn = b.isbn 
WHERE   t.isbn IS NULL;
     title     |    author     | isbn 
---------------+---------------+------
 Im a cool guy | Forrest Stone |  444
(1 row)

所以我接着尝试了

library6=# SELECT b.title, t.isbn FROM transactions t
RIGHT OUTER JOIN books b ON t.isbn = b.isbn 
WHERE t.checked_out_date >= DATEADD(year, 5, '2017/12/09') AS DateAdd   OR  
t.isbn IS NULL;
ERROR:  syntax error at or near "AS"
LINE 3: ...hecked_out_date >= DATEADD(year, 5, '2017/12/09') AS DateAdd...

理想情况我会使用timestamp自动生成当前日期,但一次只能一步。

2 个答案:

答案 0 :(得分:2)

library6=# 
SELECT b.title, b.isbn,b.author ,max(t.checked_out_date) 
    FROM transactions t
    RIGHT OUTER JOIN books b ON t.isbn = b.isbn 
    group by b.isbn, b.title
    having max(t.checked_out_date) <= (CURRENT_DATE - INTERVAL '5 
    years') 

PostgreSQL不提供dateadd功能

答案 1 :(得分:0)

你想要这样的东西:

<local:osmAppBarButton 
    ButtonState="{Binding FooBarButtonState}" 
    />

我不使用postgresql,所以我不知道它等同于dateadd。

相关问题