从数据库中获取最小时间和最长时间

时间:2016-11-15 12:04:47

标签: php mysql

我有一个MySQL表。我需要获取"最小时间"和"最长时间"通过MySQL Query。我只提取IN_AMOUT_PM。如何比较IN_AMIN_PM并比较两个时间和获取最小时间。并比较两次获取Max。 我的表是 -

enter image description here

我试过这个。但由于空栏没有工作。

SELECT *, 
       LEAST(IN_AM, IN_PM) AS intime,
       GREATEST(OUT_AM, OUT_PM) AS outtime
FROM 
       bio_attandence 
where 
       date(STR_TO_DATE(attandence_date,'%d/%m/%Y')) >= date('$startdate') 
AND 
       date(STR_TO_DATE(attandence_date,'%d/%m/%Y')) < date('$enddATE') 
AND 
       bio_id=".$row['form_no']." 
GROUP BY 
       bio_id, 
       attandence_date  
order by 
       attandence_date

2 个答案:

答案 0 :(得分:0)

您可以添加COALESCE作为空值的变通方法:LEAST(COALESCE(IN_AM, IN_PM), COALESCE(IN_PM, IN_AM)) AS intime, GREATEST(COALESCE(OUT_AM, OUT_PM), COALESCE(OUT_PM, OUT_AM)) AS outtime - 有点麻烦,但应该可以使用

答案 1 :(得分:0)

你可以这样做:

 Select IF(IN_AM IS NULL OR IN_PM IS NULL, COALESCE(IN_AM, IN_PM), LEAST(IN_AM,IN_PM)) AS intime,
 IF(OUT_AM IS NULL OR  OUT_AM IS NULL, COALESCE(OUT_AM,  OUT_AM), GREATEST(OUT_AM, OUT_AM)) AS outtime FROM bio_attandence where date(STR_TO_DATE(attandence_date,'%d/%m/%Y')) 
 >= date('$startdate') AND date(STR_TO_DATE(attandence_date,'%d/%m/%Y')) 
 < date('$enddATE') AND bio_id=".$row['form_no']." GROUP BY bio_id, 
 attandence_date  
 HAVING intime IS NOT NULL AND outtime IS NOT NULL
 order by attandence_date