sql从2表中选择并计数

mv1qrgav  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(297)

第一张table(公司)

id    Name        LOGO
1     iphone     ../763.jpg
2     Sony       ../345.jpg
3     Samsung    ../678.jpg

第二张table(操作)

id   company_id   status
1        1         new
2        1         new
3        1         repaired
4        1         Consists
5        2         new
6        2         new
7        3         repaired
8        3         Consists
9        3         repaired

结果应该是这样的

LOGO         Total      new     repaired    Consists    
../763.jpg     4         2          1          1
../345.jpg     2         2          0          0
../678.jpg     3         0          2          1
ou6hu8tu

ou6hu8tu1#

使用 join 和条件聚合:

select c.logo, count(*) as total,
       sum( status = 'new' ) as new,
       sum( status = 'repaired' ) as repaired,
       sum( status = 'consists' ) as consists,
from company c left join
     operations o
     on c.id = o.company_id
group by c.logo;
0kjbasz6

0kjbasz62#

您也可以使用下面的查询,

select 
c.logo, 
(select count(1) from operation where company_id = o.company_id group by company_id) 
as Total,
(select count(1) from operation where company_id = o.company_id and status = 'new' 
group by status) as new,
(select count(1) from operation where company_id = o.company_id and status = 
'repaired' group by status) as repaired,
(select count(1) from operation where company_id = o.company_id and status = 
'consists' group by status) as consists
from
company c
inner join operation o
on (c.id = o.company_id);

相关问题