MS SQL用“ IN”面对两个表的问题

时间:2018-11-22 08:07:16

标签: sql sql-server join

我的系统有两个表。

表1:书

enter image description here

表2:BookStatus

enter image description here

现在,我想找出在 2018/11/05至201/11/10 之间借出的图书的最新状态,以及如何他们在此期间多次被借出

我期望的结果是: enter image description here

我的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脚本以达到期望的结果?

4 个答案:

答案 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希望这对您有帮助