4

I need to get Bth working day in a month when the value of B is entered. For example, If b=12 in the month of January,2013 the resultant value should be in the date format as '17-01-2013' as the result is calculated after excluding Saturdays, Sundays & holidays in the month.

I have tried it in SQLserver with the following code & its working fine, but Im finding it difficult to execute it in MySql as some functions are not available as in Sqlserver.

    Declare 
@fromDate Date,
@Daydiff int

Set @fromDate ='01 jan 2013'

Set @Daydiff=datediff(day, @fromdate, dateadd(month, 1, @fromdate))
Select * from 
(
Select 
    dateadd(day,DayNo,@fromDate) as Date,
    dateName(weekday,(dateadd(day,DayNo,@fromDate))) As WeekDate,
    Datename(month,(dateadd(day,DayNo,@fromDate))) as MonthName,
    Row_number() Over (partition by (DatePart(month,(dateadd(day,DayNo,@fromDate)))) 
    order by (dateadd(day,DayNo,@fromDate))) as Business_day
from 
    (Select top (@Daydiff) row_number() over(order by (select 1))-1 as DayNo 
     from sys.syscolumns a cross join sys.syscolumns b)Dates
Where
    dateName(weekday,(dateadd(day,DayNo,@fromDate))) Not In ('Saturday','Sunday') and
    dateadd(day,DayNo,@fromDate) Not In (Select hdate from Holidays)
)A
Where Business_day=1

Note

Holidays is the static holidays table which contains list of holidays of 2013

I need a similar instance in Mysql. Kindly help me with this.

4

2 回答 2

2

SQLFiddle 演示

如果您需要第一天最后设置OFFSET 0。如果第二个 OFFSET 1,如果第 15 个设置 OFFSET 14

select d
FROM
(
SELECT @row := @row + 1 as row,
 DATE_ADD('2013-01-01', INTERVAL @row-1 DAY) d
from
(SELECT @row := 0) r,
(
select 1 n
union all 
select 2 n
union all 
select 3 n
union all 
select 4 n
union all 
select 5 n
union all 
select 6 n
) t1,
(
select 1 n
union all 
select 2 n
union all 
select 3 n
union all 
select 4 n
union all 
select 5 n
union all 
select 6 n
) t2
) num_seq

where 
d<DATE_ADD('2013-01-01', INTERVAL 1 MONTH)
and d not in (select hdate from Holidays )
and DAYNAME(d) not in ('Saturday','Sunday')
order by d
LIMIT 1 OFFSET 20

没有 OFFSET 和 LIMIT 的版本。看到最新where r=1的是第一天。如果您需要第 15 天更改为where r=15

SQLFiddle 演示

select d
from
(
select d,@r := @r + 1 as r
FROM
(SELECT @r := 0) r1,
(
SELECT @row := @row + 1 as row,
 DATE_ADD('2013-01-01', INTERVAL @row-1 DAY) d
from
(SELECT @row := 0) r,
(
select 1 n
union all 
select 2 n
union all 
select 3 n
union all 
select 4 n
union all 
select 5 n
union all 
select 6 n
) t1,
(
select 1 n
union all 
select 2 n
union all 
select 3 n
union all 
select 4 n
union all 
select 5 n
union all 
select 6 n
) t2
) num_seq

where 
d<DATE_ADD('2013-01-01', INTERVAL 1 MONTH)
and d not in (select hdate from Holidays )
and DAYNAME(d) not in ('Saturday','Sunday')
order by d
) rTable
where r=1
于 2013-01-21T08:45:31.720 回答
1

当仅将月份和年份作为参数传递时,如何获得相同的结果。因为当我检查代码时......它在日期是相应月份的第一天时工作,就像如果我输入参数为'2013-01-01',结果是绝对的,但如果日期是'2013-01 -15' 程序计算第 1 天第 15 天并从那里开始计算第 n 天。

于 2013-01-24T06:22:33.713 回答