BETWEEN两个日期查询

时间:2014-10-17 07:09:48

标签: sql-server between

我正在使用SQL Server 2005。

我有一个名为Books的表:

BookID
BookName
BookStatus
LoanDate
ReturnDate

我想使用BETWEEN返回范围内的BookName值。

这是捕获:

  • BookStatus为'借出'时,请在BETWEEN语句中使用LoanDate
  • BookStatus被'返回'时,请在BETWEEN语句中使用ReturnDate

代码:

SELECT BookName 
FROM Books 
  WHEN LoanDate BETWEEN '01/01/2014' AND '10/01/2014' AND BookStatus = 'Loaned'

SELECT BookName 
FROM Books 
   WHEN ReturnDate BETWEEN '01/01/2014' AND '10/01/2014' AND BookStatus = 'Returned'

如何将这些查询合并为一个?

4 个答案:

答案 0 :(得分:2)

您可以使用UNION ALL

SELECT BookName 
FROM Books 
WHERE LoanDate BETWEEN '01/01/2014' AND '10/01/2014' AND BookStatus='Loaned'

UNION ALL

SELECT BookName 
FROM Books 
WHERE ReturnDate BETWEEN '01/01/2014' AND '10/01/2014' AND BookStatus='Returned'

或者使用OR并将两个查询连接成一个。

SELECT BookName 
FROM Books 
WHERE (LoanDate BETWEEN '01/01/2014' AND '10/01/2014' AND BookStatus='Loaned')
OR (ReturnDate BETWEEN '01/01/2014' AND '10/01/2014' AND BookStatus='Returned')

答案 1 :(得分:0)

使用OR

SELECT BookName FROM Books 
WHERE (LoanDate BETWEEN '01/01/2014' AND '10/01/2014' AND BookStatus='Loaned') 
OR (ReturnDate BETWEEN '01/01/2014' AND '10/01/2014' AND BookStatus='Returned')

答案 2 :(得分:0)

SELECT BookName 
FROM Books 
WHERE LoanDate BETWEEN '01/01/2014' AND '10/01/2014' 
AND BookStatus='Loaned'

UNION ALL

SELECT BookName 
FROM Books 
WHERE ReturnDate BETWEEN '01/01/2014' AND '10/01/2014' 
AND BookStatus='Returned'

答案 3 :(得分:0)

尝试使用CASE或OR语句(它们将具有相同的执行计划),UNION ALL的成本是其两倍。

--Query cost 25%
SELECT * FROM Books WHERE 
(BookStatus = 'Loaned' AND LoanDate  BETWEEN '01/01/2014' AND '10/01/2014')
OR
(BookStatus = 'Returned' AND ReturnDate BETWEEN '01/01/2014' AND '10/01/2014')

--Query cost 25%
SELECT * FROM Books WHERE 
CASE    WHEN BookStatus = 'Loaned' THEN LoanDate  
        WHEN BookStatus = 'Returned' THEN ReturnDate END 
        BETWEEN '01/01/2014' AND '10/01/2014'

--Query cost 50%
SELECT * FROM Books WHERE BookStatus = 'Loaned' AND LoanDate  BETWEEN '01/01/2014' AND '10/01/2014'
UNION ALL
SELECT * FROM Books WHERE BookStatus = 'Returned' AND ReturnDate BETWEEN '01/01/2014' AND '10/01/2014'