我在mysql表中有长格式(如下所述)的数据,并希望将其转换为宽格式。我能否仅使用SQL完成此操作?
最好通过示例来解释。假设您具有M个国家,N个键(例如,键可以是收入、政治领袖、面积、大陆等)的(国家、键、值)信息。
Long format has 3 columns: country, key, value
- M*N rows.
e.g.
'USA', 'President', 'Obama'
...
'USA', 'Currency', 'Dollar'
Wide format has N=16 columns: county, key1, ..., keyN
- M rows
example:
country, President, ... , Currency
'USA', 'Obama', ... , 'Dollar'
在SQL中是否有一种方法可以创建一个新的表格,并将数据以宽格式存储?
select distinct key from table;
// 这将获取所有的键。
1)那么如何使用这些关键元素创建表格?
2)然后如何填充表格值?
我相信我可以用任何脚本语言(我喜欢Python)来做到这一点,但想知道是否有一种在MySQL中轻松完成此操作的方法。许多统计软件包(如R和STATA)都内置了此命令,因为它经常被使用。
======
为了更清楚,这是一个简单情况下所需的输入输出:
输入:
country attrName attrValue key (these are column names)
US President Obama 2
US Currency Dollar 3
China President Hu 4
China Currency Yuan 5
输出
country President Currency newPkey
US Obama Dollar 1
China Hu Yuan 2