我需要使用mysql查找两个日期之间的星期日数。我知道如何使用PHP来实现它但是我需要使用mysql来计算它。
答案 0 :(得分:5)
SET @START_DATE = '2014-01-22';
SET @END_DATE = '2014-06-29';
SELECT
ROUND((
(unix_timestamp(@END_DATE) - unix_timestamp(@START_DATE) ) /(24*60*60)
-7+WEEKDAY(@START_DATE)-WEEKDAY(@END_DATE)
)/7)
+ if(WEEKDAY(@START_DATE) <= 6, 1, 0)
+ if(WEEKDAY(@END_DATE) >= 6, 1, 0) as Sundays;
解决方案由两部分组成:
如果您需要多次使用它,可以将其包装到函数中:
DROP function IF EXISTS `count_weekdays`;
DELIMITER $$
CREATE FUNCTION `count_weekdays` (startDate date, endDate date, wd int)
RETURNS INTEGER
BEGIN
RETURN ROUND((
(unix_timestamp(endDate) - unix_timestamp(startDate) ) /(24*60*60)
-7+WEEKDAY(startDate)-WEEKDAY(endDate)
)/7)
+ if(WEEKDAY(startDate) <= wd, 1, 0)
+ if(WEEKDAY(endDate) >= wd, 1, 0);
END$$
DELIMITER ;
然后你就可以像这样使用它:
SET @START_DATE = '2018-07-03';
SET @END_DATE = '2018-07-28';
select
count_weekdays(@START_DATE, @END_DATE, 6) as Sundays,
count_weekdays(@START_DATE, @END_DATE, 5)
+ count_weekdays(@START_DATE, @END_DATE, 6) as weekends;
其中6~工作日代表星期日,5~星期六。
答案 1 :(得分:1)
http://sqlfiddle.com/#!2/d41d8/50695
也许有一天这个链接上没有代码所以我在这里发布了。
上部链接将显示当天的天数和星期日的日期。如果你想找到任何其他日子,最后将1改为星期一的2
select DATE_ADD('2012-12-15', INTERVAL ROW DAY) as Date,
row+1 as DayOfMonth from (
SELECT @row := @row + 1 as row FROM
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6) t1,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6) t2,
(SELECT @row:=-1) t3 limit 31
) b
where
DATE_ADD('2012-12-01', INTERVAL ROW DAY)
between '2012-12-01' and '2012-12-31'
and
DAYOFWEEK(DATE_ADD('2012-12-01', INTERVAL ROW DAY))=1
答案 2 :(得分:0)
这是否有效......
SELECT FLOOR(
(DATEDIFF(
'@enddate'
,'@startdate' + INTERVAL
LENGTH(SUBSTRING_INDEX('654321',WEEKDAY('@startdate'),1))
DAY) + 1)/7) + 1 x;
答案 3 :(得分:0)
SELECT a.StartDate, a.EndDate,
(DAY(EndDate - StartDate) / 7)
+ iif(DAY(EndDate - StartDate)%7 + DATEPART(DW, StartDate) > 8 , 1, 0)
Sundays FROM
(SELECT GETDATE() StartDate, DATEADD(DAY, 11, GETDATE()) EndDate) a
这对表中的多个开始日期和结束日期很有用。 不需要变量和循环!
工作原理:确定开始日期和结束日期之间的整周数
确定不到一周的天数,并添加开始日期索引(1,2,3,4,5,6,7),如果该值大于计数8(表示星期日!)
对于周日周日指数为1,第8天只是指数1。
答案 4 :(得分:-1)
试试这个
select count(DAYNAME(your_date_field)='Sunday') as sunday from tbl_name where your_date_field between 'date1' AND 'date2'
答案 5 :(得分:-1)
SELECT COUNT(*) FROM table_name
WHERE column BETWEEN 'start_date' AND 'end_date'
AND WEEKDAY(date) = 6;
答案 6 :(得分:-1)
参考这个,mysql有一个函数dayofweek,你可以很容易地计算开始的工作日和之后用7分的天数:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_dayofweek
OR
SELECT COUNT(*) FROM table_name
WHERE date_column_of_table_name BETWEEN '2013-01-11' AND '2013-03-01'
AND WEEKDAY(date_column_of_table_name) = 6