gpt4 book ai didi

sql - 获取两个日期之间的工作日数(周日、周一、周二)SQL

转载 作者:行者123 更新时间:2023-12-02 05:27:18 25 4
gpt4 key购买 nike

因此,对于开始日期和结束日期,我想确定这两个日期之间一周中有多少天。

那么有多少个星期一、星期二等

我知道我可以通过在开始日期和结束日期之间循环并每天检查来做到这一点,但差异可能会很大。我更喜欢不需要循环的东西。有任何想法吗? (SQL Server 2005+必须支持)

最佳答案

鉴于我认为你想要得到的,这应该做到:

SET DATEFIRST 1

DECLARE
@start_date DATETIME,
@end_date DATETIME

SET @start_date = '2011-07-11'
SET @end_date = '2011-07-22'

;WITH Days_Of_The_Week AS (
SELECT 1 AS day_number, 'Monday' AS day_name UNION ALL
SELECT 2 AS day_number, 'Tuesday' AS day_name UNION ALL
SELECT 3 AS day_number, 'Wednesday' AS day_name UNION ALL
SELECT 4 AS day_number, 'Thursday' AS day_name UNION ALL
SELECT 5 AS day_number, 'Friday' AS day_name UNION ALL
SELECT 6 AS day_number, 'Saturday' AS day_name UNION ALL
SELECT 7 AS day_number, 'Sunday' AS day_name
)
SELECT
day_name,
1 + DATEDIFF(wk, @start_date, @end_date) -
CASE WHEN DATEPART(weekday, @start_date) > day_number THEN 1 ELSE 0 END -
CASE WHEN DATEPART(weekday, @end_date) < day_number THEN 1 ELSE 0 END
FROM
Days_Of_The_Week

关于sql - 获取两个日期之间的工作日数(周日、周一、周二)SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6684577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com