gpt4 book ai didi

sql - 同时检索 'count where' 和总计数

转载 作者:行者123 更新时间:2023-12-03 18:20:59 25 4
gpt4 key购买 nike

我有一个餐厅评分和评论数据库,每家餐厅可能有 1 到 1000 条评论。

我首先尝试查找哪些餐厅的评论中包含“taco”这个词的评论最多 4+,然后我使用下面的代码让它工作:

    select id, count(id) from test where (comment like '%taco%') AND rating >= 3 group by id order by count(id) DESC;

因此,例如,如果 X 餐厅有 30 条 4+ 包含“taco”的评分评论,我会为该行获得“X|30”。

我想添加两个附加功能:
  • 列出每家餐厅的评论总数(无条件)
  • 对包括“taco”在内的所有餐厅评论进行平均评分。

  • 如果餐厅 X 总共有 150 条评论,其中 30 条评分为 4+,包括“taco”,这 30 条评论的平均评分为 2.5,我会得到:

    'X|30|150|2.5|'

    我如何得到这个结果?

    最佳答案

    这样的事情可能会奏效。

    select id
    , count(*) totalreviews
    , sum(case when rating >= 3 and comment like '%taco%' then 1 else 0 end) ratings4plus
    , avg(case when rating >= 3 and comment like '%taco%' then rating else null end) avgratings4plus
    from test
    group by id

    关于sql - 同时检索 'count where' 和总计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15347194/

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