如何使用MySQL进行透视?

时间:2016-07-22 07:16:12

标签: mysql pivot

我有一个MySQL表:

enter image description here

我想要输出类似下面的内容(旋转类型),Pen Pencil和Glue列中的值必须从最近的时间戳填充。

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以通过执行子查询的透视来实现结果,该子查询标识每个Category - Product组的最新记录。

SELECT t1.Category,
       MAX(CASE WHEN t1.Product = 'pen'    THEN CONCAT(t1.Flag, '(productid-', t1.Product_ID, ')') ELSE NULL END) AS Pen,
       MAX(CASE WHEN t1.Product = 'pencil' THEN CONCAT(t1.Flag, '(productid-', t1.Product_ID, ')') ELSE NULL END) AS Pencil,
       MAX(CASE WHEN t1.Product = 'glue'   THEN CONCAT(t1.Flag, '(productid-', t1.Product_ID, ')') ELSE NULL END) AS Glue
FROM yourTable t1
INNER JOIN
(
    SELECT Category, Product, MAX(timestamp) AS timestamp
    FROM yourTable
    GROUP BY Category, Product
) t2
    ON t1.Category  = t2.Category AND
       t1.Product   = t2.Product AND
       t1.timestamp = t2.timestamp
GROUP BY t1.Category

请按照以下链接查看正在运行的演示:

SQLFiddle

答案 1 :(得分:0)

试试这个:

select
    Category,
    max(case when Product = 'pen' then concat(`Flag`, '(productid-', Product_ID, ')') else null end) as `Pen`,
    max(case when Product = 'pencil' then concat(`Flag`, '(productid-', Product_ID, ')') else null end) as `Pencil`,
    max(case when Product = 'glue' then concat(`Flag`, '(productid-', Product_ID, ')') else null end) as `Glue`
from (
    select t1.*
    from yourtable t1
    join (
        select Product, Category, max(`timestamp`) as `timestamp`
        from yourtable
        group by Product, Category
    ) t2 on t1.Product  = t2.Product and t1.`timestamp` = t2.`timestamp` and t1.Category = t2.Category
) t
group by Category