带有除法的sqlite嵌套查询

sqlite nested query with division

我对 SQL 有点陌生,想知道最好的方法。基本上一个查询 return 是分母,而外部查询需要 return numerator/denominator 作为百分比。每个语句基本上使用相同的表。

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

输出: star wars, .3(因为 3 star wars sets out of 10 sets and star wars is a top game) 口袋妖怪,0.1(因为 10 套中有 1 套口袋妖怪,也是顶级套装) 最后我们将它限制为仅 2 个顶级套装,因此塞尔达套装不会出现。

如果你有 SQLite 3.25.0+,你可以使用 window 函数:

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              |