Mysql 查询以提取密钥->;将值表转换为列式表
考虑下表:Mysql 查询以提取密钥->;将值表转换为列式表,mysql,sql,Mysql,Sql,考虑下表: itemid itemkey itemvalue ---------------- ------------- ------------ 123 Colour Red 123 Size Medium 123 Fabric Cotton 是否
itemid itemkey itemvalue
---------------- ------------- ------------
123 Colour Red
123 Size Medium
123 Fabric Cotton
是否有一个简单的查询来获取类似以下内容:
itemid Colour Size Fabric
---- ---- --- ---
123 Red Medium Cotton
124 Yellow Large Poly
...
编辑
当除所有标记外的第一个表包含日期时,还有一个变量,在透视中,您需要选择最新的标记,例如:
itemid itemkey itemvalue date
---------------- ------------- ------------ ------
123 Colour Red 2017-03
123 Colour Yellow 2017-04
123 Size Medium
123 Fabric Cotton
因此,对于记录123,颜色应该是黄色,而不是红色,因为它的日期是前一个日期,这称为数据透视,如果项目数是动态的,则应该在应用程序代码中完成 如果项目事先已知,则可以使用条件聚合:
select itemid,
max(case when itemkey = 'Colour' then itemvalue end) as Colour,
max(case when itemkey = 'Size' then itemvalue end) as Size,
max(case when itemkey = 'Fabric' then itemvalue end) as Fabric,
. . .
from your_table
group by itemid;
如果有基于日期的版本控制,则可以使用子查询查找最新记录,然后执行数据透视:
select itemid,
max(case when itemkey = 'Colour' then itemvalue end) as Colour,
max(case when itemkey = 'Size' then itemvalue end) as Size,
max(case when itemkey = 'Fabric' then itemvalue end) as Fabric,
. . .
from your_table t
join (
select itemid, itemkey
max(date) as date
from your_table
group by itemid, itemkey
) t2 using (itemid, itemkey, date)
group by itemid;
谢谢GurV+1!我对我的问题进行了编辑,添加了一个稍微困难的查询,例如:当每个标记都有一个日期,而您只需要提取最新的日期时,有没有简单的方法?没有进入每组最多n个问题的兔子洞?@giò更新了答案。这太令人印象深刻了。。。这也可能是解决每组最多n个问题的最好方法