我想获得StartDate和EndDate之间的区别,但如果差异小于0,我想要值0(EndDate可能在StartDate之前)。有没有办法在SELECT中执行此操作而不重复ROUND()表达式?
SELECT StartDate, EndDate,
IF(ROUND(TIMESTAMPDIFF(SECOND, StartDate, EndDate)/86400, 1) < 0, 0, ROUND(TIMESTAMPDIFF(SECOND, StartDate, EndDate)/86400, 1)) AS Duration
FROM table
WHERE StartDate <= '2016-06-02' AND EndDate >= '2016-06-01';
答案 0 :(得分:3)
只需使用GREATEST()
即可获得较大的0和差异。
SELECT StartDate, EndDate,
GREATEST(ROUND(TIMESTAMPDIFF(SECOND, StartDate, EndDate)/86400, 1), 0) AS Duration
FROM table
WHERE StartDate <= '2016-06-02' AND EndDate >= '2016-06-01';