使用MySql获取特定日期

时间:2013-01-21 08:09:55

标签: mysql sql-server

我需要在输入B值的一个月内获得Bth工作日。 例如,如果在2013年1月份b = 12,则结果值应采用日期格式为'17 -01-2013',因为计算结果 在排除星期六,星期日和星期日之后这个月的假期。

我在SQLserver中尝试过以下代码&它工作正常,但我发现很难在MySql中执行它,因为有些功能不是 在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

注意

假期是静态假期表,其中包含2013年假期列表

我在Mysql中需要一个类似的实例。 请帮助我。

2 个答案:

答案 0 :(得分:2)

SQLFiddle demo

如果你需要第一天设置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 demo

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

答案 1 :(得分:1)

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