如何使用 MySQL 进行旋转?

How to do pivoting with MySQL?

我有一个 MySQL table:

我想要如下所示的输出(有点旋转),必须从最近的时间戳填充 Pen Pencil 和 Glue 列中的值。

您可以通过为每个 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

按照下面的 link 进行 运行 演示:

SQLFiddle

试试这个:

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