MySQL计算具有特定值的行

时间:2014-06-04 19:49:18

标签: mysql sql

我有一张这样的表:

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

我想要这样的结果:

accept_status decline_status user_id
   2                 1         7
   0                 2         8

2 个答案:

答案 0 :(得分:0)

使用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;

答案 1 :(得分:0)

架构(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);

查询 #1subqueries 操作期间使用了两个 SELECT

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;

查询 #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

输出

<头>
accept_status decline_status user_id
2 1 7
0 2 8

View on DB Fiddle