合并行并给出总计数

时间:2016-07-30 12:36:06

标签: mysql sql-server join count group-by

我想知道用户玩了多少个独特的游戏。以下是当前SQL查询的外观:

SELECT COUNT(DISTINCT d.id_game) AS c
FROM discord AS d
JOIN discord_games AS dg
ON d.id_game = dg.id
WHERE d.id_user = '1'
AND d.id_game != '0'
GROUP BY d.id_game
ORDER BY dg.data_name ASC

现在这里的数据库看起来像:

CREATE TABLE IF NOT EXISTS `discord` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `id_user` int(11) NOT NULL,
  `id_channel` varchar(50) NOT NULL,
  `id_game` int(11) NOT NULL,
  `data_muted_server` tinyint(4) NOT NULL,
  `data_muted_self` tinyint(4) NOT NULL,
  `data_deafen_server` tinyint(4) NOT NULL,
  `data_deafen_self` tinyint(4) NOT NULL,
  `data_suppressed` tinyint(4) NOT NULL,
  `data_status` varchar(10) NOT NULL,
  `datetime_logged` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)


CREATE TABLE IF NOT EXISTS `discord_games` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data_name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)


CREATE TABLE IF NOT EXISTS `discord_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data_id` text NOT NULL,
  `data_name` varchar(50) NOT NULL,
  `data_avatar` text,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

SQL查询计算正确,但每行只计数1个。

我正在思考的例子。如果ID为1的用户已玩过24次相同的游戏(例如“战地3”),它将返回1个游戏。如果同一个用户玩了37次其他游戏,它将返回2个玩过的游戏,依此类推。

SUM(DISTINCT ...不起作用,因为它只用游戏ID替换1。

如何对行进行求和,使其显示数字2而不是2行?

1 个答案:

答案 0 :(得分:0)

您可以按属性删除该组,并计算所播放的不同游戏。它将返回用户1放置的不同游戏包的数量

block in <main>'
      from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:48:in