我对SQL有点陌生,我想知道这样做的最佳方法。基本上,一个查询返回分母,而外部查询则需要返回分子/分母。每个语句基本上使用相同的表。
create table games(
id integer NOT NULL,
name TEXT NOT NULL,
category TEXT NOT NULL
);
create table game_sets(
id integer NOT NULL,
name TEXT NOT NULL,
theme_id integer NOT NULL
);
INSERT INTO games (id, name, category)
VALUES (1, "star wars", "top game"),
(2, "pokemon", "top game"),
(3, "zelda", "top game"),
(4, "crazy cats", "sucky game");
INSERT INTO game_sets(id, name, theme_id)
VALUES (1, "star wars set 1", 1),
(2, "star wars set 2", 1),
(3, "star wars set 3", 1),
(4, "pikachu set 1", 2),
(5, "narf set 1", 4),
(6, "narf set 2", 4),
(7, "narf set 1", 4),
(8, "narf set 1", 4),
(9, "narf set 1", 4),
(10, "narf set 1", 4);
CREATE VIEW top_games AS
SELECT id, name
FROM games
WHERE category ='top game';
--i hard coded 200 below, but it needs to be dynamic
select top_games.name as theme, printf("%.2f", cast(count(game_sets.name)as float)/200) as num_sets_percent from top_games
join game_sets
where top_games.id = game_sets.theme_id
group by top_games.id
order by num_sets desc
limit 2;
--below here is the number i need for the first query to divide
--i have it hard coded as 4 b/c 4 total sets in the game_sets table, but it needs to be dynamic with this query
(select count(game_sets.name) as num_sets from game_sets
join top_games
where top_games.id = game_sets.theme_id) as divide_by_this
输出: 星球大战,.3(因为在10套游戏中总共有3个星球大战,而星球大战是头号游戏) 宠物小精灵,0.1(因为10个小精灵中总共设置了1个小精灵,所以它也是排名第一的小精灵) 最后,我们只将其限制在前两个设置中,以免塞尔达设置不出现。
答案 0 :(得分:1)
如果您拥有SQLite 3.25.0+,则可以使用窗口函数:
select distinct
g.name,
1.0 * count(g.id) over (partition by g.id) / count() over () num_sets_percent
from game_sets s left join top_games g
on s.theme_id = g.id
order by num_sets_percent desc
limit 2
请参见demo。
结果:
| name | num_sets_percent |
| --------- | ---------------- |
| star wars | 0.3 |
| pokemon | 0.1 |