昨天获得的纯粹MySQL方式是什么,但仅限于工作日?
现在我昨天使用SUBDATE(CURRENT_DATE, 1))
,但周一它将在周日返回。
我希望它能够返回上周五的日期结果,换句话说,也就是前一个工作日的结果。
我应该澄清我试图在查询的WHERE
部分(以及子查询)中使用它。
SELECT ... WHERE DATE(timestamp) = SUBDATE(CURRENT_DATE, 1))
以下是整个查询:
SELECT r.drivername, l.branchcity as location, COUNT(o.ordernum) as deliveries, COUNT(x.pictures) as pics, CONCAT(ROUND((COUNT(x.pictures) / COUNT(o.ordernum))*100,2),'%') as percentage_having_images
FROM deliveries d, drivers r, locations l, staging s, stations t, orders o LEFT OUTER JOIN
(SELECT a.ordernum AS pictures
FROM orders a WHERE a.stationID = '16' AND DATE(a.scantime) = SUBDATE(CURRENT_DATE, 1)) x
ON x.pictures = o.ordernum
WHERE o.deliveryID = d.ID AND d.driverID = r.ID AND s.locationID = l.ID AND o.stationID = t.ID AND o.stagingID = s.ID AND t.ID IN ('11','12','13') AND DATE(o.scantime) = SUBDATE(CURRENT_DATE, 1) GROUP BY s.locationID, r.drivername ORDER BY s.locationID, percentage_having_images DESC
答案 0 :(得分:8)
SELECT ..
.
.
AND DATE(a.scantime) = (CASE WEEKDAY(CURRENT_DATE)
WHEN 0 THEN SUBDATE(CURRENT_DATE,3)
WHEN 6 THEN SUBDATE(CURRENT_DATE,2)
WHEN 5 THEN SUBDATE(CURRENT_DATE,1)
ELSE SUBDATE(CURRENT_DATE,1)
END)
..
..
答案 1 :(得分:0)
试试这个来结束这一天:
SELECT
CASE DAYOFWEEK(SUBDATE(CURRENT_DATE, 1))
WHEN 1 THEN SELECT SUBDATE(CURRENT_DATE, 3);
WHEN 7 THEN SELECT SUBDATE(CURRENT_DATE, 2);
ELSE
BEGIN
SUBDATE(CURRENT_DATE, 1);
END;
END CASE;
然后使用子查询
SELECT ... WHERE DATE(timestamp) = (SELECT
CASE DAYOFWEEK(SUBDATE(CURRENT_DATE, 1))
WHEN 1 THEN SELECT SUBDATE(CURRENT_DATE, 3);
WHEN 7 THEN SELECT SUBDATE(CURRENT_DATE, 2);
ELSE
BEGIN
SUBDATE(CURRENT_DATE, 1);
END;
END CASE);
答案 2 :(得分:0)
好的,所以不是最容易阅读的解决方案,而是更短更冷。 ; - )
SELECT CURRENT-DATE - if((6+weekday(@dat))%7 > 4, (6+weekday(@dat))%7-3, 1) as prev_workday
解释:至少在我的时区给出工作日('星期一 - 日期')= 0,在星期日6。用+6
我将它转移到6 .. 12.使用modulu 7( %7
)我将其转移到星期六= 4,星期日= 5,星期一= 6。
因此,在大于4的那个班次之后的所有日子里,我减少了这个价值的日期 - 3,否则我会在#39;之前的那一天。所以在周六我减少一天,周日减少两天,周一减少三天。