我有一個部門出租系統。因此,用戶可以租用一個部門,并且網站上不會提供日期。
所以我可以有一個部門有一些日期,比如:
開始日期:'2022-04-11'結束日期'2022-04-14'
和開始日期'2022-04-16' EndingDate'2022-04-18'
所以,正如你所看到的,該部門有可用的一天'2022-04-15'
如果兩個日期之間有可用日期,我想要一個選擇陳述句bit true or false,所以如果我的日期是
'2022-04-11'并且 '2022-04-18',它應該回傳一個真值,因為'2022-04-15'它是可用的。我怎樣才能做到這一點?問候
uj5u.com熱心網友回復:
您還需要生成一個日期表 - 以便您在 DATES 表中每天都有一行。
然后,您可以使用外連接將 DATES 表連接到主表,并檢查主表端的 NULLS 以進行驗證。
-- Using your sample values, create a RENTAL table
CREATE TABLE Rentals (
RentalID INT IDENTITY(1,1),
StartDate DATE NOT NULL,
EndDate DATE NOT NULL
) ;
INSERT Rentals (StartDate, EndDate)
VALUES ('2022-04-11', '2022-04-14'), ('2022-04-16', '2022-04-18')
GO
-- Create the DATES table
CREATE TABLE DatesTable (
DateName DATE NOT NULL
);
GO
-- Populate it for this year
DECLARE @inc INT = 365
WHILE @inc > 0
BEGIN
INSERT DatesTable (DateName)
SELECT DATEADD(DAY, @inc, '2021-12-31') ;
SELECT @inc = @inc - 1 ;
END
GO
SELECT d.DateName, CASE WHEN r.StartDate IS NULL THEN 'TRUE' ELSE 'FALSE' END as IsAvailable
FROM DatesTable d
LEFT JOIN Rentals r ON d.DateName >= r.StartDate AND d.DateName <= r.EndDate
WHERE d.DateName BETWEEN '2022-04-11' and '2022-04-18'
ORDER BY d.[DateName] ASC
uj5u.com熱心網友回復:
DepartmentTable:
name
start_date
end_date
parameter
@bookingDate
select count(*) from
Department
where @bookingDate between start_date and end_date
如果您的計數大于 0,則它不可用
uj5u.com熱心網友回復:
我認為你可以使用視窗函式來實作你想要的。我不熟悉 SQL Server,但我用 Google 搜索,它似乎支持我的查詢(我在 Postgres 中寫的)。
create temporary table rentals (
id serial primary key,
starts_at date,
ends_at date
);
insert into rentals (starts_at, ends_at) values
('2022-01-05', '2022-01-6'),
('2022-01-08', '2022-01-14'),
('2022-01-15', '2022-01-16'),
('2022-01-18', '2022-01-20');
with r as (
select id,
starts_at,
ends_at,
lead(starts_at, 1) over(order by starts_at asc) as next_starts_at
from rentals
)
select
(
CASE count(id)
WHEN 0 THEN false
ELSE true
END
) as available
from r
where
( ends_at interval '1 day' < next_starts_at OR next_starts_at IS NULL ) AND
ends_at >= '2022-01-03' AND
ends_at < '2022-01-05'
上面首先使用視窗函式創建了一個 CTE,lead以查找任何給定行的下一個開始日期。
select id,
starts_at,
ends_at,
lead(starts_at, 1) over(order by starts_at asc) as next_starts_at
from rentals
id | starts_at | ends_at | next_starts_at
---- ------------ ------------ ----------------
1 | 2022-01-05 | 2022-01-06 | 2022-01-08
2 | 2022-01-08 | 2022-01-14 | 2022-01-15
3 | 2022-01-15 | 2022-01-16 | 2022-01-18
4 | 2022-01-18 | 2022-01-20 |
然后它選擇您想要的范圍之間的日期
ends_at >= '2022-01-03' AND
ends_at < '2022-01-05'
并且還選擇了租金
- 他們的結束日期和下一次租賃的開始日期之間至少有一天的差距
( ends_at interval '1 day' < next_starts_at )
- 或者是系統中記錄的最后一次出租,因此在最后一次出租之后肯定有空房
OR next_starts_at IS NULL
我在一系列日期上對此進行了測驗,假設我正確理解了您的要求,它似乎可以作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460702.html
上一篇:簡化查詢SQL
下一篇:SQL用單個字符替換多個字符
