mysql 将多行转换为单行中的列
我有一个包含列的详细信息表:
- user_id int
- code int
- value int
我想构建一个如下所示的汇总表:
- user_id int
- valueA int
- valueB int
在详细信息表中, valueA 将对应于代码 5, valueB 将对应就是说,代码 6,所以我正在寻找类似的内容:
插入摘要 (user_id,valueA,valueB) VALUES (从详细信息中选择 ???);
当然,问题是我正在查看“详细信息”表中的多行以填充“摘要”表中的一行。
例如,如果我有以下详细信息:
1 5 100
1 6 200
2 5 1000
2 6 2000
我想在汇总表中得到以下内容:
1 100 200
2 1000 2000
有什么想法吗?
i have a details table with columns:
- user_id int
- code int
- value int
And i want to build a summary table that looks like:
- user_id int
- valueA int
- valueB int
In the details table, valueA would correspond to say, code 5, and valueB would correspond to say, code 6, so i'm looking for something like:
insert into summary (user_id,valueA,valueB) VALUES ( SELECT ??? from details );
The problem of course is that i'm looking at multiple rows from the "details" table to populate one row in the "summary" table.
Eg, if i had the following rows in details:
1 5 100
1 6 200
2 5 1000
2 6 2000
I want to end up with the following in the summary table:
1 100 200
2 1000 2000
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
MySQL 没有 PIVOT/UNPIVOT 语法,这使您只能使用 GROUP BY 和 CASE 表达式的组合:
MySQL doesn't have PIVOT/UNPIVOT syntax, which leaves you to use a combination of GROUP BY and CASE expressions:
请注意:如果 user_id+code 不唯一,您最终会得到多个摘要列。
编辑:
beware: you will end up with multiple summary columns if user_id+code is not unique.
EDIT:
如果您有一组可管理的代码(例如仅 5 和 6),您可以执行以下操作:
您可能需要修改您的
JOIN
,具体取决于您的代码是否不需要作为 1 对 1 关系(即LEFT JOIN
)。如果您有大量代码,我会研究游标在代码结果集上运行类似的查询或使用不同的技术(即 PHP 脚本)。
If you have a manageable set of codes (say just 5 and 6) you could do something like this:
You may need to modify your
JOIN
s depending on if your codes are not required as 1 to 1 relationship (i.e.LEFT JOIN
s).If you have a large set of codes, I would look into a cursor runs a similar query above over a result set of your codes or using a different technology, (i.e. PHP script).