您好我有关于SQL结构的问题。我有一些想通了,但我不能得到其余的。
USERS TABLE
user OS_signup
1 Mobile
2 Windows
3 Mac
4 Mobile
5 Windows
DUNGEON TABLE
user dungeon progress status OS_completed deaths
1 Dungeon 1 1 finished Windows 0
1 Dungeon 1 2 incomplete Windows 0
2 Dungeon 2 1 finished Windows 1
3 Dungeon 2 1 finished Mac 1
3 Dungeon 1 2 finished Mac 3
3 Dungeon 3 3 incomplete Mac 0
4 Dungeon 1 1 finished Mobile 1
5 Dungeon 1 1 incomplete Windows 5
在比较完成第一个地牢的第一级进度的用户与在游戏中拥有帐户的用户的百分比时,哪种操作系统最受欢迎?
我有这个查询
SELECT OS_signup, count(*) AS count_total
FROM users
GROUP BY OS_signup
和这一个
SELECT OS_completed, count(*) AS count_completed
FROM dungeons
WHERE dungeon = "Dungeon 1" AND progress >=1 AND status = "finished"
GROUP BY OS_completed
我显然得到了两个表,但是我想编写一个输出组合表的查询,以便得到一个看起来像这样的表:
OS percent-done
Mobile 0.5
Windows 0.5
Mac 1
如何编写查询来实现上述表格?
谢谢!
答案 0 :(得分:1)
对于MySQL,它可能是这样的:
SELECT OS_signup, count(*) AS count_total, COUNT(tmp.user_id) as count_completed, COUNT(tmp.user_id) / COUNT(*) as percent
FROM users
LEFT JOIN (
SELECT user_id
FROM dungeons
WHERE dungeon = 'Dungeon 1' AND progress >= 1 AND status = 'finished'
GROUP BY user_id
) tmp ON tmp.user_id = users.id
GROUP BY OS_signup
答案 1 :(得分:0)
只需将这两个查询的结果加在一起:
WITH total(OS, count_total) AS (
SELECT OS_signup, count(*)
FROM users
GROUP BY OS_signup
),
completed(OS, count_completed) AS (
SELECT OS_completed, count(*)
FROM dungeons
WHERE dungeon = 'Dungeon 1'
AND progress >= 1
AND status = 'finished'
GROUP BY OS_completed
)
SELECT OS,
count_total,
count_completed,
CAST(count_completed AS FLOAT) / count_total AS percent
FROM total
JOIN completed USING (OS)
ORDER BY ...;
(MySQL没有公用表表达式;你必须使用视图或子查询。)