简体   繁体   English

如何在JOIN表中使用SQL CASE和COUNT

[英]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 tbl_student和tbl_trns_clr示例如果所有办公室状态都已清除,则备注清除,否则如果一个办公室未清除,则备注不清除

在此输入图像描述

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使用标量表达式,而不是显式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. AB这样A随机字母只会使查询难以理解。
  • You don't need to use COUNT(*) . 您不需要使用COUNT(*) NOT EXISTS is more appropriate and has better performance -- because it can stop at the first value that matches. NOT EXISTS更合适,性能更好 - 因为它可以停在匹配的第一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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