简体   繁体   English

从具有多个相似行的表中选择不同的行

[英]Selecting distinct rows from a table with several similar rows

I'm trying to list all cars that are available for rent between two specific dates, using a procedure.我正在尝试使用程序列出在两个特定日期之间可供出租的所有汽车。 The table of which I am to select from, bookings, looks similar to this;我从预订到 select 的表格与此类似;

CarNumber    StartDate    EndDate
1            2018-01-03   2018-01-05
2            2018-01-09   2018-01-14
3            2018-01-03   2018-01-04
2            2018-01-29   2018-02-2
3            2018-01-12   2018-01-16

This is my current procedure;这是我目前的程序;

CREATE PROCEDURE available_cars (Start_Date DATE, End_Date DATE)
READS SQL DATA
    BEGIN
        SELECT DISTINCT CarNumber FROM bookings
        WHERE NOT StartDate BETWEEN Start_Date AND End_Date
           OR NOT EndDate BETWEEN Start_Date AND End_Date;
    END;

This, to my knowledge, correctly checks if the car is rentable between, Start_Date and End_Date, the issue is that it cannot take into account several rows with the same CarNumber.据我所知,这可以正确检查汽车是否可在 Start_Date 和 End_Date 之间租用,问题是它不能考虑具有相同 CarNumber 的几行。 For example, if I were to call the procedure with the dates 2018-01-10 to 2018-01-12 the output will display;例如,如果我要调用日期为 2018-01-10 到 2018-01-12 的过程,则会显示 output;

CarNumber
1
3
2

Obviously Car 3 and Car 2 is not available to be rented between these dates, but due to the table including several bookings on several rows it checks the second booking as well.显然,Car 3 和 Car 2 在这些日期之间不可租用,但由于该表包括几行上的多个预订,因此它也会检查第二个预订。

So how do I account for this?那么我该如何解释呢?

If you don't store unique key in your database you can make compound query checking rented cars between selected dates and then making a DIFF between all available cars and currently rented.如果您没有在数据库中存储唯一键,您可以在选定日期之间进行复合查询检查租用的汽车,然后在所有可用汽车和当前租用的汽车之间进行 DIFF。

SELECT DISTINCT CarNumber
FROM bookings
WHERE CarNumber NOT IN (
        SELECT CarNumber FROM bookings
        WHERE StartDate BETWEEN Start_Date AND End_Date
        OR EndDate BETWEEN Start_Date AND End_Date)
        OR (StartDate < Start_Date AND EndDate > End_Date;

You can easily create procedure from that code.您可以轻松地从该代码创建过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM