尝试按日期筛选SQL结果
我有一个图书馆的数据库,我正试图写一个查询,以返回所有五年未借出的书籍 它应该产生像这样的东西尝试按日期筛选SQL结果,sql,postgresql,Sql,Postgresql,我有一个图书馆的数据库,我正试图写一个查询,以返回所有五年未借出的书籍 它应该产生像这样的东西 isbn | title | author ------+---------------------+--------------- 222 | The Art of the Deal | Trump 444 | Im a cool guy | Forrest Stone (2 rows) 我有一张书桌子 library6=# SEL
isbn | title | author
------+---------------------+---------------
222 | The Art of the Deal | Trump
444 | Im a cool guy | Forrest Stone
(2 rows)
我有一张书
桌子
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)
我有一个交易
表
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...
理想情况下我会使用
时间戳
自动生成当前日期,但每次只生成一个步骤 你想要这样的东西:
select isbn, title, max(checked_out_date)
from books join transactions on books.isbn = transactions.isbn
group by isbn, title
having max(checked_out_date) <= dateadd(year, 5, current_date)
选择isbn、标题、最大值(签出日期)
从图书加入图书上的交易。isbn=交易。isbn
按isbn分组,标题
拥有max(签出日期)你想要这样的东西:
select isbn, title, max(checked_out_date)
from books join transactions on books.isbn = transactions.isbn
group by isbn, title
having max(checked_out_date) <= dateadd(year, 5, current_date)
选择isbn、标题、最大值(签出日期)
从图书加入图书上的交易。isbn=交易。isbn
按isbn分组,标题
拥有max(签出日期)library6=#
选择b.title、b.isbn、b.author、max(t.checked\u out\u date)
来自交易t
t.isbn=b.isbn上的右外连接书本b
按b.isbn、b.title分组
拥有max(t.签出日期)library6=#
选择b.title、b.isbn、b.author、max(t.checked\u out\u date)
来自交易t
t.isbn=b.isbn上的右外连接书本b
按b.isbn、b.title分组
最大值(t.签出日期)