select
RESTAURANT,
RANK,
(select count(SCORE)
from TRIPADVISOR
where score = 4) as totalfour,
(select count(*)
from TRIPADVISOR) as total
from
TRIPADVISOR
我知道SQL有一个平均功能。我的问题是,我有一个TRIPADVISOR表,其中包含Resturant名称,等级(1-10)和客户审查的得分(1-5)的列。我想通过将要计数的元素总数()来计算得分为4的总人数的百分比。我该怎么做?我在select子句中进行两个子查询的地方进行了设置,该子句显示了给出4的总人数以及为count()的条目总数以及Resturant名称列表和所有队伍。谢谢。
答案 0 :(得分:1)
您可以尝试使用计数的CASE
SELECT
RESTAURANT,
RANK,
((COUNT(CASE WHEN score = 4 THEN 1 END) * 1.0) / COUNT(*))*100 AS PercentageScore4
FROM TRIPADVISOR
GROUP BY RESTAURANT, RANK;
答案 1 :(得分:0)
如果每个餐厅都想要这个:
$('#main-menu .navbar-header .col-xs-6:first-child, #main-menu .navbar-header button')
.on('click touchstart', function(){
// your code here
})
如果要在整个数据库中使用它,
select restaurant,
avg(case when score = 4 then 1.0 else 0 end) as avg_4
from TRIPADVISOR
group by restaurant;
如果要将其附加到每一行,请使用窗口函数:
select avg(case when score = 4 then 1.0 else 0 end) as avg_4
from TRIPADVISOR ;