我在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'
但是可以创建一个唯一的查询来获取此统计信息吗?
答案 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