使用mysql在一个查询中查询计数,总和,条件

时间:2016-04-22 07:51:57

标签: mysql sql

我在mysql数据库中有这个表:

TABLE rating
| id         (int, primary)
| id_company (int, index)
| state      (enum: 'waiting','done','refuse')
| rating     (int between 1 and 5)

我想获取一个id_company的统计信息:

  • 数字行
  • 状态=已完成的数字行
  • 总和评级
  • 与州=完成的总和评级

为此我有2个查询(例如id_company = 2):

SELECT COUNT(1) as `nbr`, SUM(`rating`) as `total` FROM `rating` WHERE `id_company`=2
SELECT COUNT(1) as `nbr`, SUM(`rating`) as `total` FROM `rating` WHERE `id_company`=2 AND `state`='done'

但是可以创建一个唯一的查询来获取此统计信息吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

SELECT COUNT(*) as `nbr1`, 
       SUM(`rating`) as `total1`,
       SUM(`state`='done') as `nbr2`, 
       SUM(CASE 
              WHEN `state`='done' THEN `rating` 
              ELSE 0 
           END) as `total2`  
FROM `rating` 
WHERE `id_company`=2