SQL如何从当天开始提前7天查看

时间:2015-12-13 17:30:27

标签: sql

我有以下查询:

SELECT Booking.StaffID, Booking.BookingStatus, Car.StartDate, Car.ReturnDate, Car.CarMake, Car.CarModel
FROM Booking
INNER JOIN Car
ON Booking.BookingNo=Car.BookingNo
WHERE StartDate - ??

我希望能够在当天自动查看StartDate预订的后7天内的情况。我该怎么做?

1 个答案:

答案 0 :(得分:2)

要过滤每个日期的查询,我更喜欢使用两个过滤器而不是两者之间。这里有一些不同数据库(Oracle,MySQL和MSSQL)的示例。请注意,您必须在第二个过滤器中添加额外的一天"<"。你将增加8而不是7天。我还从过滤日期中删除了时间。

甲骨文:

SELECT
    Booking.StaffID, 
    Booking.BookingStatus, 
    Car.StartDate, 
    Car.ReturnDate, 
    Car.CarMake, 
    Car.CarModel
FROM 
    Booking
    INNER JOIN Car
    ON Booking.BookingNo = Car.BookingNo
WHERE 
    Car.StartDate >= trunc(sysdate)
    AND Car.StartDate < trunc(sysdate + 8)
;

MySQL的:

SELECT
    Booking.StaffID, 
    Booking.BookingStatus, 
    Car.StartDate, 
    Car.ReturnDate, 
    Car.CarMake, 
    Car.CarModel
FROM 
    Booking
    INNER JOIN Car
    ON Booking.BookingNo = Car.BookingNo
WHERE 
    Car.StartDate >= date(sysdate())
    AND Car.StartDate < date_add(date(sysdate()), INTERVAL 8 day)
;

MSSQL:

SELECT
    Booking.StaffID, 
    Booking.BookingStatus, 
    Car.StartDate, 
    Car.ReturnDate, 
    Car.CarMake, 
    Car.CarModel
FROM 
    Booking
    INNER JOIN Car
    ON Booking.BookingNo = Car.BookingNo
WHERE 
    Car.StartDate >= DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
    AND Car.StartDate < DATEADD(dd, DATEDIFF(dd, 0, getdate()), 8)
;