Sqlite:从两个相关列中获取模态/模式

时间:2015-05-15 06:07:04

标签: sql sqlite

这是GAMES表中的摘录:

ID  WUSER       BUSER
1   ddyer       bdot
2   ddyer       ronaldinho
3   bluedog     ronaldinho
4   ronaldinho  bluedog
5   bluedog     ronaldinho
6   ddyer       bobc
7   bobc        ddyer

该表是来自boardpace.net网站的数据库,其中人们玩棋盘游戏。在数据库中,wuser和buser用于白人和黑人玩家,id是游戏。现在我想知道发挥最多的球员。所以我为白人玩家做这件事:

 SELECT wuser, count(wuser) 
 FROM game 
 GROUP BY wuser 
 ORDER BY count(wuser) DESC;

结果是:

wuser    count(wuser)
Dumbot   75926
guest    22541
image13  1594
DrRaven  1460
Eucalyx  1147
Loizz    963

然后我必须为黑人球员做同样的事情:

 SELECT buser, count(buser) 
 FROM game 
 GROUP BY buser 
 ORDER BY count(buser) DESC;

buser    count(buser)
Dumbot   59489
guest    29324
Eucalyx  1007
image13  756
DrRaven  746
Loizz    715
alexis   660

我可以像下面一样手动加总,但是如何从单个SQL语句中获取结果:

user     count(as both buser and wuser)
Dumbot   135412
guest    51865
image13  2350
DrRaven  2206

我只想知道每个玩家的游戏总数,我不感兴趣他们是白色还是黑色。

2 个答案:

答案 0 :(得分:1)

当你为每个用户获得大量行时,你最好在UNION之前计算COUNT并添加另一个聚合步骤:

SELECT usr, sum(cnt)
FROM
 (
   SELECT wuser as usr, count(*) as cnt
   FROM game 
   GROUP BY wuser

   UNION ALL

   SELECT buser, count(*) 
   FROM game 
   GROUP BY buser
 ) AS dt
 GROUP BY usr
 ORDER BY sum(cnt) DESC;

答案 1 :(得分:0)

您可以使用UNION取消对桌子的取消操作。然后只需GROUP BY用户名和COUNT

SELECT usr, COUNT(usr)
FROM (
   SELECT WUSER AS usr 
   FROM GAMES

   UNION ALL

   SELECT BUSER AS usr 
   FROM GAMES ) u
GROUP BY usr
ORDER BY COUNT(usr) DESC

SQL Fiddle Demo