我有下表:
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/