如何通过SQL将表中的垂直字段转换为水平结果
我有一个这样的表:
create table t1 {
person_id int,
item_name varchar(30),
item_value varchar(100)
};
假设 person_id+item_name 是复合键,现在表 t1 中有一些数据(5 条记录),如下所示:
person_id ====item_name ====== item_value
1 'NAME' 'john'
1 'GENDER' 'M'
1 'DOB' '1970/02/01'
1 'M_PHONE' '1234567890'
1 'ADDRESS' 'Some Addresses unknown'
现在我想使用 SQL(或组合存储过程/函数或其他)来查询上面的结果(1个结果集)变成:
NAME==GENDER==DOB========M_PHONE=======ADDRESS===============
1 M 1970/02/01 1234567890 Some Addresses unknown
我该怎么办? 感谢您的帮助。
I have a table like this:
create table t1 {
person_id int,
item_name varchar(30),
item_value varchar(100)
};
Suppose person_id+item_name is the composite key, now I have some data (5 records) in table t1 as below:
person_id ====item_name ====== item_value
1 'NAME' 'john'
1 'GENDER' 'M'
1 'DOB' '1970/02/01'
1 'M_PHONE' '1234567890'
1 'ADDRESS' 'Some Addresses unknown'
Now I want to use SQL (or combing store procedure/function or whatever) to query the above result (1 result set) become:
NAME==GENDER==DOB========M_PHONE=======ADDRESS===============
1 M 1970/02/01 1234567890 Some Addresses unknown
How should I do ?
Thank you for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无论您使用什么数据库,您想要实现的概念都称为“数据透视表”。
这是 mysql 的一个例子:
http://en.wikibooks.org/wiki/MySQL/Pivot_table
一些数据库内置了有关功能,请参阅下面的链接。
SQL服务器:
http://msdn.microsoft.com/de-de/library/ms177410.aspx甲骨文
:
http://www.dba-oracle.com/t_pivot_examples.htm
您随时可以创建用手转动枢轴。只需选择结果集中的所有聚合,然后从该结果集中进行选择即可。请注意,在您的情况下,您可以使用 concat 将所有名称放入一列中(我认为这是 mysql 中的 group_concat ),因为您无法知道有多少名称与 person_id 相关。
Regardless of the database you are using, the concept of what you are trying to achieve is called "Pivot Table".
Here's an example for mysql:
http://en.wikibooks.org/wiki/MySQL/Pivot_table
Some databases have builtin features for that, see the links below.
SQLServer:
http://msdn.microsoft.com/de-de/library/ms177410.aspx
Oracle:
http://www.dba-oracle.com/t_pivot_examples.htm
You can always create a pivot by hand. Just select all the aggregations in a result set and then select from that result set. Note, in your case, you can put all the names into one column using concat (i think that's group_concat in mysql), since you cannot know how many names are related to a person_id.
最后在PostgreSQL中找到了解决方案:
还需要在Postgres上安装crosstab功能。查看更多: http://www.postgresql.org/docs/8.3/static/ tablefunc.html
Finally, I found the solution in PostgreSQL:
Also need to install the crosstab function on Postgres. See more: http://www.postgresql.org/docs/8.3/static/tablefunc.html