我一直在使用MySQL中的动态数据透视表作为引用here,它工作正常。在我的情况下,我的表也有一个时间戳列。我想在数据透视表中返回属性的最新值,但我无法弄清楚如何完成此操作。因此,请考虑示例表数据:
+---------+--------+--------+--------+
| item_id | color | size | weight |
+---------+--------+--------+--------+
| 1 | purple | large | 69 |
+---------+--------+--------+--------+
对于item_id' 1'结果行应为:
{{1}}
提前致谢!
答案 0 :(得分:0)
你的问题有点棘手。我们可以使用子查询来查找每个项目和属性的最新记录。然后,将表连接到此子查询并执行常规数据透视查询以生成所需的输出。
SELECT
t1.item_id,
MAX(CASE WHEN t1.property_name = 'color' THEN t1.value END) AS color,
MAX(CASE WHEN t1.property_name = 'size' THEN t1.value END) AS size,
MAX(CASE WHEN t1.property_name = 'weight' THEN t1.value END) AS weight
FROM yourTable t1
INNER JOIN
(
SELECT item_id, property_name, MAX(timestamp) AS max_timestamp
FROM yourTable
GROUP BY item_id, property_name
) t2
ON t1.item_id = t2.item_id AND
t1.property_name = t2.property_name AND
t1.timestamp = t2.max_timestamp
WHERE
t1.item_id = 1
GROUP BY t1.item_id;
item_id | color | size | weight
1 | purple | large | 69