2012-01-26 65 views
-1

表之間的所有周五和節假日:如何找到兩個日期

hDate  Holiday 

17/12/2011 National Day 
01/01/2012 New Year 
.... 

從表中,我想找到兩個日期之間的假期總數:

的查詢,如:

select count(hdate) 
from table1 
where hdate between '" & start_date & "' and '" & end_date & "' 

用戶輸入:

start_date = '16/12/2011' 
end_date = '15/01/2012' 

,我也想找到兩個日期之間的星期五。

查找星期五,如何創建查詢?

預期輸出:

Holiday Friday 

2  5 

[2] - 從表1 2天假期,[5] - 5星期週五

如何做到這一點?

回答

5

這計數週五2日期間:

declare @from datetime= '2012-01-26' 
declare @to datetime = '2012-01-28' 

select datediff(day, -3, @to)/7-datediff(day, -2, @from)/7 

假期很容易找到,好像你有部分覆蓋了。

我早些時候回答了這個問題。但沒有得到任何信用:

How to calculate the number of "Tuesdays" between two dates in TSQL?

1
select count(Holiday) as holiday 
from Table1 
where date between start_date AND end_date 
1
DECLARE @StartDate DATETIME 
DECLARE @EndDate DATETIME 
SET @StartDate ='16/12/2011' 
SET @EndDate = '15/01/2012' 


SELECT 
    (DATEDIFF(dd, @StartDate, @EndDate) + 1) 
    -(DATEDIFF(wk, @StartDate, @EndDate) * 2) 
    -(CASE WHEN DATENAME(dw, @StartDate) = 'Friday' THEN 1 ELSE 0 END) 
1

參見:

Why should I consider using an auxiliary calendar table?

日曆表可以使它更容易地圍繞任何涉及日期的任何 業務模型開發解決方案。 最後我檢查了一下,這包括幾乎任何商業模式 ,你可以在一定程度上想到 。恆 問題,最終需要 冗長,複雜和低效 方法包括以下 問題:X和Y之間

  • 多少個工作日?
  • 3月的第二個星期二到4月的第一個星期五之間的所有日期是什麼?
  • 我應該預計該貨件到達哪個日期?
  • 本季度所有星期五的日期是什麼?
  • ...
1

我們有一個額外的時間表解決問題。這看起來像這樣

ID | Date  | Holiday | Year | CalendarWeek | DayName 
1 | 17/12/2011 | 1   | 2011 | 50   | Monday 
2 | 18/12/2011 | 0   | 2011 | 50   | Thursday 
3 | 19/12/2011 | 0   | 2011 | 50   | Wendsday 

有了這張表,你可以解決這樣的

select 
(select count(d.DayName) from date_table as d 
    where d.DayName = 'Friday' and date >= start_date and date <= end_date), 
(select sum(d.Holiday) from date_table as d 
    where date >= start_date and date <= end_date) 

這個你的問題也應該是SQL Server 2000的兼容。而這對於SQL Server 2005及以上:

with tmp(id) as 
(
select id from from date_table where date >= start_date and date <= end_date 
) 
select 
(select count(d.DayName) from date_table inner join tmp on tmp.id = id 
    where DayName = 'Friday'), 
(select sum(d.Holiday) from date_table inner join tmp on tmp.id = id) 
2

那選擇幫助你:

DECLARE @FROMDATE DATE = '2009-01-07' 
DECLARE @TODATE DATE = '2012-01-26' 

SELECT COUNT(*) holidays,(select COUNT(*) from table1 where DATEPART(DW, hdate) = 5 
AND DT BETWEEN @FROMDATE AND @TODATE) fridays FROM table1 
WHERE hdate BETWEEN @FROMDATE AND @TODATE 
相關問題