【问题标题】:how to get the desired result based on some certain condition in sql using case?如何根据 sql 使用案例中的某些特定条件获得所需的结果?
【发布时间】:2020-10-22 06:51:18
【问题描述】:

我有一个表格,可以跟踪用户记录,我想知道哪些是完整的,并根据用户的状态处理用户记录

这里是sql查询

SELECT users.UserID,users.UserName,users.FirstName,users.LastName,users.Email,
CASE WHEN inword.inword_status = '3' THEN  count(*) END As 'Process' ,
CASE WHEN inword.inword_status = '4' THEN  count(*) END AS 'Complete' 
FROM tbl_user users
INNER JOIN tbl_inword inword on users.UserID=inword.UserID 
Where inword.Status=1 and users.Status=1 and 
inword.CreatedDate BETWEEN '2020-10-01' and '2020-10-31' and inword.inword_status in (3)
group by  users.UserID

这是查询输出

我的预期结果是

UserID  Name      Total    Process     Complete
1       Umair     1           1           0
1       Basit     20          20          0
1       Zaidi     34          32          2

任何帮助将不胜感激

【问题讨论】:

    标签: mysql group-by case-when


    【解决方案1】:

    你没有正确地做你的条件聚合,你应该使用类似的东西:

    COUNT(CASE WHEN inword.inword_status = '3' THEN inword.UserId END) As 'Process' ,
    COUNT(CASE WHEN inword.inword_status = '4' THEN inword.UserId END) AS 'Complete' 
    

    或者您可以利用 MySQL 在数字上下文中将布尔值视为 10 并简化为:

    SUM(inword.inword_status = '3') As 'Process' ,
    SUM(inword.inword_status = '4') AS 'Complete' 
    

    【讨论】:

    • @UmairMubeen 不用担心 - 我很高兴能提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2016-10-11
    • 2014-09-09
    • 2020-10-13
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多