我在MySQL数据库中有以下数据:
选择是1还是0.我想在每部电影后创建一个带有百分比选择(1s)的谷歌图表。我可以在excel中生成如下:
有没有办法生成具有这些运行总计的结果,而无需在表格中创建新列? (类似于SUM)
第一行应该是1,但设置为0只是为了让图表看起来更好!
答案 0 :(得分:1)
第一行应该是100%,对吗? 1票,1票等于100%
create table runningp(id int auto_increment primary key, choice tinyint);
insert into runningp(choice) values (1),(0),(0),(1),(1),(0),(1),(1),(0),(0);
select r.*, @p:=@p+choice, @t:=@t+1, @p/@t as yes
from runningp r,
(select @p:=0, @t:=0) v
order by id;
+----+--------+---------------+----------+--------+
| id | choice | @p:=@p+choice | @t:=@t+1 | yes |
+----+--------+---------------+----------+--------+
| 1 | 1 | 1 | 1 | 1.0000 |
| 2 | 0 | 1 | 2 | 0.5000 |
| 3 | 0 | 1 | 3 | 0.3333 |
| 4 | 1 | 2 | 4 | 0.5000 |
| 5 | 1 | 3 | 5 | 0.6000 |
| 6 | 0 | 3 | 6 | 0.5000 |
| 7 | 1 | 4 | 7 | 0.5714 |
| 8 | 1 | 5 | 8 | 0.6250 |
| 9 | 0 | 5 | 9 | 0.5556 |
| 10 | 0 | 5 | 10 | 0.5000 |
+----+--------+---------------+----------+--------+
只需选择您需要的内容:
select id, choice, yes from (
select r.*, @p:=@p+choice, @t:=@t+1, @p/@t as yes
from runningp r,
(select @p:=0, @t:=0) v
order by id
) sq
order by id;
+----+--------+--------+
| id | choice | yes |
+----+--------+--------+
| 1 | 1 | 1.0000 |
| 2 | 0 | 0.5000 |
| 3 | 0 | 0.3333 |
| 4 | 1 | 0.5000 |
| 5 | 1 | 0.6000 |
| 6 | 0 | 0.5000 |
| 7 | 1 | 0.5714 |
| 8 | 1 | 0.6250 |
| 9 | 0 | 0.5556 |
| 10 | 0 | 0.5000 |
+----+--------+--------+
10 rows in set (0.00 sec)
答案 1 :(得分:1)
假设@fancyPants是正确的(通常是),那么你也可以这样写(稍微简单,可扩展性较差)......
SELECT x.*
, SUM(y.choice)/COUNT(*) * 100 pct
FROM film_choice x
JOIN film_choice y
ON y.film <= x.film
GROUP
BY x.film;