gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:50:12 27 4
gpt4 key购买 nike

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

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

我想获取一个 id_company 的统计数据:

  • 数行
  • state=done 的行数
  • 综合评分
  • 总评分为 state=done

为此我有 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'

但是可以进行唯一查询来获取此统计信息吗?

最佳答案

你可以尝试这样的事情:

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

关于mysql - 使用mysql在一个查询中查询计数,总和,带条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36788023/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com