简体   繁体   English

MySQL 计算具有特定值的行

[英]MySQL count rows with specific value

I have a table like this:我有一张这样的表:

id  status     user_id
 1  decline     8
 2  approved    7
 3  approved    7   
 4  decline     8
 5  decline     7

I want result like this:我想要这样的结果:

accept_status decline_status user_id
   2                 1         7
   0                 2         8

Schema (MySQL v5.7)架构 (MySQL v5.7)

CREATE TABLE TEST (
  id int,
  status varchar(20),
  user_id int
  );
  
INSERT INTO TEST
VALUES(1,'decline',8);
 INSERT INTO TEST
VALUES(2,'approved',7);
 INSERT INTO TEST
VALUES(3,'approved',7);
 INSERT INTO TEST
VALUES(4,'decline',8);
 INSERT INTO TEST
VALUES(5,'decline',7);

Query #1 Used two subqueries during SELECT operation查询 #1SELECT操作期间使用了两个subqueries

SELECT 
 (SELECT count(status) FROM TEST b WHERE status='approved' AND b.user_id = a.user_id) as accept_status, 
 (SELECT count(status) FROM TEST c WHERE status='decline' AND c.user_id = a.user_id) as decline_status, 
 a.user_id
FROM TEST a
GROUP BY user_id;

OR或者

Query #2查询#2

SELECT 
    sum(case when status = 'approved' then 1 else 0 end) AS accept_status,
    sum(case when status = 'decline' then 1 else 0 end) AS decline_status,
    user_id
FROM TEST
GROUP BY user_id

Output输出

accept_status接受状态 decline_status下降状态 user_id用户身份
2 2 1 1 7 7
0 0 2 2 8 8

View on DB Fiddle在 DB Fiddle 上查看

Using SubQuery or Sub Select you can try this query:使用 SubQuery 或 Sub Select 你可以试试这个查询:

select distinct user_id,
(select count(*) from testtable 
     where status='approved' and user_id=a.user_id) as accept_status,
(select count(*) from testtable 
     where status='decline' and user_id=a.user_id) as denied_status
from testtable a;

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

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