mysql - SQL如何对给定范围的列进行分组并连接到其他表以计算与第一列相关的行

标签 mysql sql postgresql table-relationships

我需要根据给定的年份范围对用户列进行分组。这是示例年份范围 (1980-1989,1990-1999,2000-2009) 然后,我需要加入以计算另一个表的结果。我创建了一个数据库“user_relations”,并创建了两个表来显示我的问题。

+--------------------------+
| Tables_in_user_relations |
+--------------------------+
| user_answers             |
| users                    |
+--------------------------+
2 rows in set (0.00 sec)

这是用户表

+----+----------+-----------+
| id | username | birthyear |
+----+----------+-----------+
|  1 | user1    |      1980 |
|  2 | user2    |      1990 |
|  3 | user3    |      2000 |
|  4 | user4    |      1983 |
+----+----------+-----------+
4 rows in set (0.00 sec)

这是 user_answers 表。我只需要根据按日期范围分组的用户来计算 user_answers。

+----+---------+-----------+
| id | user_id | option_id |
+----+---------+-----------+
|  1 |       1 |         1 |
|  2 |       2 |         1 |
|  3 |       3 |         2 |
|  4 |       4 |         1 |
+----+---------+-----------+
4 rows in set (0.00 sec)

根据这些表格,我需要得到类似这样的结果。

+------------------------------------------------
| option_id | 1980-1989 | 1990-1999 | 2000-2009 |
+------------------------------------------------
|  1        |         2 |         1 |         0 |
|  2        |         0 |         0 |         1 |
|  3        |         0 |         0 |         0 |
+------------------------------------------------

注意:我需要先使用用户表。我知道可能会有很多变化来获得这个结果。但是我必须以这种方式得到结果。这只是一个例子。

我希望那边有人能帮助我。谢谢。

最佳答案

为此,您可以在总和中使用 case 语句,非常简单:

select ua.option_id,
       sum(case when u.birthyear between 1980 and 1989 then 1 else 0 end) as "1980-1989",
       sum(case when u.birthyear between 1990 and 1999 then 1 else 0 end) as "1990-1999",
       sum(case when u.birthyear between 2000 and 2009 then 1 else 0 end) as "2000-2009"
from   users as u
inner  join user_answers as ua
on     ua.user_id = u.id
group  by ua.option_id

关于mysql - SQL如何对给定范围的列进行分组并连接到其他表以计算与第一列相关的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41654958/

相关文章:

MySQL,无法创建 UNIX 套接字 (12)

python - 根据错误显示定制的异常消息

sql - 根据sql中的日期过滤数据

mysql - SQL Join 与代码聚合

sql - Postgresql按乱序排序

postgresql - 如何创建名称中包含点的 Postgres 数据库?

c# - 如何使用来自文本框的输入并在 C# 的 mysql 查询中使用它

php - 我在 win xp 上安装了 php5.2.9 +mysql 5.1+apache2.2.6 。iam 无法让 php 连接到 mysql

php - Mysql通过取错时间戳查询分组

sql - 复杂的 Join Query,Join 3 tables with multiple group bys