如何根据 sql 使用案例中的某些特定条件获得所需的结果?

how to get the desired result based on some certain condition in sql using case?

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

这是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

任何帮助将不胜感激

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

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'