mysql - 根据行数将数据从行连接到 1 行

标签 mysql sql

我有下表:

user
userId   name
1        Sam
2        Harold
3        John


othertable
id      id2      number
1       111      12
1       222      23
1       333      33
2       111      12
2       444      11
3       555      12
3       222      44

用户表的 userId 与其他表的 id 列匹配。理想情况下,我想根据该 id 存在的行数将 othertable 的内容加入到用户中。这就是我想要的输出:

e.g.
user
    userId   name    111    222   333   444   555
    1        Sam     12     12    33
    2        Harold  12                 11
    3        John           44                12

有什么想法吗?

更新:id2 的值是有限的。仅有效值 111、222、333、444 和 555。

最佳答案

您可以尝试一下这个1...不确定它是否满足您的要求...

CREATE TABLE users 
(
    userId int,
    name varchar(max)
) 

INSERT INTO USERS VALUES
(1, 'Sam'),
(2, 'Harold'),
(3, 'John')

CREATE TABLE othertable 
(
    id int,
    id2 int,
    number int
)

INSERT INTO othertable VALUES
(1, 111, 12),
(1, 222, 23),
(1, 333, 33),
(2, 111, 12),
(2, 444, 11),
(3, 555, 12),
(3, 222, 44)

SELECT
    u.userId,
    u.name,
    SUM(CASE WHEN (id2=111) THEN number ELSE 0 END) AS [111],
    SUM(CASE WHEN (id2=222) THEN number ELSE 0 END) AS [222],
    SUM(CASE WHEN (id2=333) THEN number ELSE 0 END) AS [333],
    SUM(CASE WHEN (id2=444) THEN number ELSE 0 END) AS [444],
    SUM(CASE WHEN (id2=555) THEN number ELSE 0 END) AS [555]
FROM othertable o 
INNER JOIN users u ON o.id = u.userId
GROUP BY u.userId, u.name

请尝试一下。 :)

UPDATE: Sorry, I'm not really familiar with MySQL. But I did tried my best by changing the query into subquery and hope this can help you. If this doesn't meet you requirement, I hope some other people can help you.

UPDATE 2: Avoid using PIVOT

关于mysql - 根据行数将数据从行连接到 1 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40102210/

相关文章:

c# - 使用 C# 将 SQL Server 数据导出到 Excel?

sql - 如何用匹配调用 regexp_replace 中的函数?

MySQL:任何改进最佳匹配存储过程的建议

sql - 用单行表示 SQL 结果 - 以阶梯结束

sql - Node SQL Server mssql 流

mysql - 我在 Windows 10 上运行 mysql,如何从 WSL 连接到其端口

mysql - Rails - 如何加入基于单个 View 的两个关系?

mysql - 了解 aws 和 rds 连接

javascript - 为什么我的查询结果不会显示在 Express 上的表中?

mysql - 选择不同的表并对其他表进行计数