简体   繁体   中英

How use SQL CASE & COUNT in JOIN Table

enter image description here I want to summarize the student's clearance status into a single result using join query. tbl_student and tbl_trns_clr example if all office status is Cleared then remarks is Cleared else if one office is not cleared then remark is Not Cleared

在此输入图像描述

SELECT *
FROM `tbl_student` as A join
     `tbl_trns_clr` as B 
     on B.EDP = A.EDP AND
        CASE WHEN (SELECT COUNT(*)
                   FROM tbl_trns_clr
                   WHERE B.clr_status = 'Not Cleared' AND A.EDP = B.EDP
                  ) = 0 THEN 'Cleared'
         END) as clr_status

and I wanna make it appear like the Table UI

You seem to just want a scalar expression in the SELECT , not an explicit JOIN :

SELECT s.*,
       (CASE WHEN EXISTS (SELECT 1
                          FROM tbl_trns_clr c
                          WHERE c.clr_status = 'Not Cleared' AND
                                c.EDP = s.EDP
                         )
             THEN 'Cleared' ELSE 'Not Cleared'
         END) as clr_status
FROM `tbl_student` s;

Notes:

  • Use table aliases that are meaningful . Random letters like A and B just make the query hard to follow.
  • You don't need to use COUNT(*) . NOT EXISTS is more appropriate and has better performance -- because it can stop at the first value that matches.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM