我的系统有两个表。
表1:书
表2:BookStatus
现在,我想找出在 2018/11/05至201/11/10 之间借出的图书的最新状态,以及如何他们在此期间多次被借出。
我期望的结果是:
我的SQL脚本是:
SELECT BK.*,
BS.status, BS.statusDateTime,
(SELECT count(*) FROM BookStatus WHERE status='lent' AND bookId=BK.bookId AND statusDateTime>='2018/11/05 00:00:00' AND statusDatetime<='2018/11/10 23:59:59' ) CountLent
FROM Book BK LEFT JOIN BookStatus BS ON BK.bookId = BS.bookId
WHERE BS.statusId = (SELECT max(statusId) FROM BookStatus WHERE bookId= BK.bookId)
AND BK.bookId IN (SELECT bookId FROM BookStatus WHERE status='lent' AND statusDateTime>='2018/11/05 00:00:00' AND statusDatetime<='2018/11/10 23:59:59')
执行sql查询后,它只会继续运行并且不会停止。 我的SQL查询有问题吗? 如何修改我的SQL脚本以达到期望的结果?
答案 0 :(得分:2)
请尝试如下查询-
select b.bookid ,b.bookName , b.Author
,bs.status ,max(bs.statusDatetime), count(bs.status) Countlent
from Book b
join BookStatus bs on b.bookid= bs.bookid
where bs.statusDateTime >='2018/11/05 00:00:00' AND bs.statusDatetime<='2018/11/10 23:59:59'
and bs.status = 'lent'
group by b.bookid ,b.bookName , b.Author ,bs.status
希望这会对您有所帮助。
答案 1 :(得分:1)
使用子查询找出该期间借出的所有书籍和计数。使用CROSS APPLY
获取最新状态:
WITH activity AS (
SELECT bookId, COUNT(*) AS CountLent
FROM BookStatus
WHERE statusDateTime >= '2018-11-05' AND statusDateTime < DATEADD(DAY, 1, '2018-11-10')
AND status = 'lent'
GROUP BY bookId
)
SELECT Book.*, activity.CountLent, lastStatus.*
FROM Book
INNER JOIN activity ON Book.bookId = activity.bookId
CROSS APPLY (SELECT TOP 1 status, statusDateTime FROM BookStatus WHERE bookId = Book.bookId ORDER BY statusDateTime DESC) AS lastStatus
答案 2 :(得分:0)
您可以在下面尝试
select b.bookid ,b.bookName , b.Author ,bs.status ,
max(bs.statusDatetime) as statusDatetime, count(bs.status) Countlent
from Book b
join BookStatus bs on b.bookid= bs.bookid
where bs.statusDateTime >='2018/11/05 00:00:00' AND bs.statusDatetime<='2018/11/10 23:59:59' and bs.status = 'lent'
group by b.bookid ,b.bookName , b.Author ,bs.status
答案 3 :(得分:0)
我尝试运行您的代码,没关系,但是结果不正确!您可以尝试以下方法:
SELECT bd.bookID, bk.bookName, bk.author,
statusID, status, statusDateTime ,bc.countLent
FROM ( SELECT bookID, statusDate = MAX(statusDateTime)
FROM bookStatus
GROUP BY bookID
) AS bd
LEFT JOIN ( SELECT bookID, COUNT(*) AS countLent
FROM bookStatus
WHERE [status] = 'lent'
GROUP BY bookID
) AS bc ON bc.bookID = bd.bookID
LEFT JOIN dbo.bookStatus ON bookStatus.bookID = bc.bookID
AND bd.statusDate = dbo.bookStatus.statusDateTime
LEFT JOIN Book AS bk ON bk.bookID = bookStatus.bookID
结果很好,但是我知道我的代码不是最好的方法:D希望这对您有帮助