简体   繁体   中英

Select Count days between two dates using LINQ

I need to get the number of holidays between two dates. I have tried using the query below but I'm getting an incorrect count number.

StartDate EndDate
01/2/2022 03/2/2022
17/2/2022 19/2/2022
SELECT COUNT(*) FROM table
WHERE StartDate <= '02/2/2022' and EndDate >= '19/2/2022'

how I make this date => '02/2/2022' return count of day that between two dates from the first row from the table and get count day from the second row.

The count must be 5 days.

The simplest way of doing it is to have a table that has one row per day for every day from eg year 2000 to year 2099, then you can:

SELECT COUNT(*) 
FROM
  cal           --your dates table
  INNER JOIN h. --your holiday table 
  ON cal.d BETWEEEN h.start AND h.end
WHERE
  cal.d BETWEEN '2022-02-02' AND '2022-02-19'

The join will produce 6 rows, the where trims it to 5, there is your count

Generating the calendar table, or its equivalent (an arbitrary series of dates) is an exercise for the reader.. See something like this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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