在跨越同一表中两列的日期范围之间记录

时间:2019-03-06 13:40:56

标签: php mysql sql mysqli phpmyadmin

我必须获取跨越2列的日期范围之间的记录。

between statusEnteredDate and newDate in the image(Please click here)

到目前为止,我已经尝试了下面的代码,但这似乎并没有考虑newDate列。

我还要考虑在newColumn中具有价值的那一行

SELECT *, COALESCE(`status_data`.`statusEnteredDate`, `status_data`.`newDate`) as twinData,
       count(*) as MY_COUNT
FROM `status_data`
WHERE (`status_data`.`statusEnteredDate` BETWEEN '2019/02/24 10:00' AND '2019/03/01 10:00'
       OR `status_data`.`newDate` BETWEEN 'null' AND '2019/02/27 10:00')
GROUP By `recordUniqueID`
ORDER by `id` ASC

我需要在此处保留GROUP By,因为我还希望得到重复行的计数。

还有什么方法可以在COALESCE的同一SQL查询中应用逻辑?因为这样我就可以将两列合并在一起。如下所示:

SELECT *, COALESCE(`status_data`.`statusEnteredDate`, `status_data`.`newDate`) as twinData,
       count(*) as MY_COUNT
FROM `status_data`
WHERE (`twinData` BETWEEN '2019/02/24 10:00' AND '2019/02/27 10:00')
GROUP By `recordUniqueID`
ORDER by `id` ASC

以上代码没有给我想要的结果。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您在null周围加上单引号,因此将其解释为零。而且您没有正确处理NULL比较。我想你想要

select . . .
from status_data sd
where (sd.statusEnteredDate >= '2019-02-24 10:00' and
       sd.statusEnteredDate < '2019-03-01 10:00'
      ) and
      (sd.newDate is null or
       sd.newDate < '2019-02027 10:00'
      )