如何在mysql中编写case语句?

时间:2015-05-23 05:51:27

标签: mysql

这里我想要当前日期和输入日期的日期差异。在下面我写了case语句,但是它为curdate()返回NULL。.whats出错了吗?

SELECT admit_patient_details.admit_pat_doctor,admit_patient_details.admit_pat_dept,admit_patient_details.admit_pat_name,
                admit_patient_details.admit_pat_room_no,admit_patient_details.admit_pat_bed_no
                ,patient.patient_name,patient.in_date,patient.discharge_date,
                CASE patient.discharge_date
                    WHEN '0000-00-00' THEN DATEDIFF(curdate(),patient.in_date)
                    ELSE DATEDIFF(patient.discharge_date,patient.in_date)
                END AS totaldays FROM admit_patient_details,patient 
                having admit_patient_details.admit_pat_name=patient.patient_name

一些列输出:

admit_pat_name |  in_date   |   discharge_date |     totaldays   |
Satish Mokashi |2015-05-19  |  2015-05-22      |     3           |
guddi jagtap   |2015-05-12  |  2015-05-20      |     8           |
Rahul Patil    |2015-04-17  |  NULL            |     NULL        |

1 个答案:

答案 0 :(得分:1)

您的专栏默认为NULL而不是0000-00-00。所以你可以尝试一下:

SELECT 
  admit_patient_details.admit_pat_doctor,
  admit_patient_details.admit_pat_dept,
  admit_patient_details.admit_pat_name,          
  admit_patient_details.admit_pat_room_no,
  admit_patient_details.admit_pat_bed_no,
  patient.patient_name,
  patient.in_date,
  patient.discharge_date,
  CASE
    WHEN patient.discharge_date IS NULL THEN DATEDIFF(curdate(),patient.in_date)
    ELSE DATEDIFF(patient.discharge_date,patient.in_date)
  END AS totaldays 
FROM admit_patient_details,patient 
HAVING admit_patient_details.admit_pat_name=patient.patient_name