我正在尝试编写一个SQL查询,该查询将创建过去一个月内已检出的所有图书的列表,以及每本图书已签出多长时间。
我有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
4 | 2017-12-06 | | 4 | 111
5 | 2017-11-29 | 2017-12-04 | 5 | 555
6 | 2017-11-28 | 2017-12-05 | 1 | 333
(6 rows)
我的一些更接近的失误是
library6=# SELECT DISTINCT books.title, books.author FROM books LEFT OUTER JOIN transactions ON books.isbn = transactions.isbn ;
title | author
---------------------------------------+---------------
Harry Potter and the Sorcerer’s Stone | JK Rowlings
rich i am | Bill Gates
The Art of the Deal | Trump
Im a cool guy | Forrest Stone
to catch a crook | Robert Muller
(5 rows)
答案 0 :(得分:0)
在mysql中你可以使用datediff(),sum()和group by
SELECT b.title
, b.author
, sum(DATEDIFF(t.checked_in_date , t.checked_out_date)) num_days
FROM books b
LEFT JOIN transactions t ON b.isbn = t.isbn
group by b.title, b.author
答案 1 :(得分:0)
对于postgre:
select b.isbn,
b.title,
b.author,
sum(DATE_PART('day', coalesce(t.checked_in_date, CURRENT_DATE), greatest(t.checked_out_date, CURRENT_DATE+ interval '-1 month'))) days_checked_out
from books b
join transactions t on b.isbn = t.isbn
where t.checked_out_date between CURRENT_DATE+ interval '-1 month' and CURRENT_DATE
or t.checked_in_date between CURRENT_DATE+ interval '-1 month' and CURRENT_DATE
group by b.isbn,
b.title,
b.author;
如果您还需要显示过去一个月未签出的图书,可以为SUM添加左连接和合并。