繁体   English   中英

sql select 并从 2 个表中计数

[英]sql select and Count from 2 Table

第一表(公司)

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

第二表(操作)

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

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

您也可以使用以下查询,

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);

暂无
暂无

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

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