使用group by子句使用汇总计数值执行平均值

时间:2018-11-28 08:00:40

标签: sql

表为

Food ID  | Food Review
1        | good Review
1        | good Review
1        | Bad Review
2        | good Review
2        | Bad Review
3        | Good Review

预期的输出是

Food ID   | Good Review | All Review | Acceptance score
1         | 2           | 3          | 2/3

接受分数将计算为“良好评论/所有评论”

任何人都可以帮助我进行查询吗?

2 个答案:

答案 0 :(得分:0)

您可以在下面尝试

select 
    foodid, 
    count(case when FoodReview='good Review' then 1 end) as GoodReview,
    count(*) as allreview, (count(case when FoodReview='good Review' then 1 end)*1.0)/count(*) as Acceptancescore
from tablename
group by foodid

答案 1 :(得分:0)

这将起作用:

CREATE TABLE Tab
    ("a" int, "b" varchar2(11))
;

INSERT ALL 
    INTO Tab ("a", "b")
         VALUES (1, 'good Review')
    INTO Tab ("a", "b")
         VALUES (1, 'good Review')
    INTO Tab ("a", "b")
         VALUES (1, 'Bad Review')
    INTO Tab ("a", "b")
         VALUES (2, 'good Review')
    INTO Tab ("a", "b")
         VALUES (2, 'Bad Review')
    INTO Tab ("a", "b")
         VALUES (3, 'good Review')
SELECT * FROM dual
;

select * from Tab;
select t1."a",count(t1."b")
from Tab t1
group by t1."a";

select m.*,m.GoodReview||'/'||all_review "ACCEPTANCE" from 
(select 
ta."a" ,
(select count(*) from Tab where 
"a"=ta."a"  and
"b"='good Review' group by "a")GoodReview,
(select count(*) from Tab where "a"=ta."a" group by ta."a") all_review
from 
Tab ta
group by ta."a") m ;

output:
1   2   3   2/3
2   1   2   1/2
3   1   1   1/1