MySQL-如何根据另一列中的唯一值转置一列中的单元格?

问题描述 投票:0回答:1

我需要从Magento 1.9数据库中获取我们所有的产品类别,并将其显示在一行中,并显示我设法获取的'产品ID','产品类型','sku'和'类别路径'(ID和值)多行返回我对每种产品的所有类别的时间点。我当前的查询如下:

SELECT 
    p.entity_id AS 'product_id',
    p.type_id AS 'product_type',
    p.sku,
    c.category_id,
    l.level AS 'category_level',
    l.path AS 'category_path',
    n.name AS 'category_name'
FROM
    mage_catalog_product_entity AS p
        JOIN
    mage_catalog_category_product_index AS c ON p.entity_id = c.product_id
        JOIN
    mage_catalog_category_entity AS l ON l.entity_id = c.category_id
        JOIN
    mage_catalog_category_flat_store_6 AS n ON n.path = l.path
WHERE
    c.store_id = '6' 
        AND l.path LIKE '1/14%'
        AND l.path NOT LIKE '1/14/207%'
        AND l.path NOT LIKE '1/14/12/25%'
        -- AND l.level > 1
ORDER BY p.sku , length(l.path)

它返回以下内容:

“当前查询结果屏幕截图”

我想要达到的目标是这样的:

“所需的查询结果屏幕截图”

或者,理想情况下,将这些列合并为一个

“理想的查询结果屏幕截图”

有什么建议吗?

sql magento pivot categories transpose
1个回答
0
投票
从您现有的查询开始,这是一种按产品ID,产品类型和SKU进行分组,并使用类别级别将类别名称分布在各列中的方法:

SELECT p.entity_id AS product_id, p.type_id AS product_type, p.sku, max(l.level) AS category_level, max(l.path) AS category_path, max(case when l.level = 1 then n.name end) AS level1_category_name, max(case when l.level = 2 then n.name end) AS level2_category_name, max(case when l.level = 3 then n.name end) AS level3_category_name, max(case when l.level = 4 then n.name end) AS level4_category_name FROM mage_catalog_product_entity AS p JOIN mage_catalog_category_product_index AS c ON p.entity_id = c.product_id JOIN mage_catalog_category_entity AS l ON l.entity_id = c.category_id JOIN mage_catalog_category_flat_store_6 AS n ON n.path = l.path WHERE c.store_id = '6' AND l.path LIKE '1/14%' AND l.path NOT LIKE '1/14/207%' AND l.path NOT LIKE '1/14/12/25%' GROUP BY product_id, p.entity_id, p.sku ORDER BY p.sku

附带说明:列别名不要使用单引号;尽管某些数据库可能支持这一点,但SQL标准指出单引号用于文字字符串。为您的数据库使用正确的引号字符,或者最好使用不需要引号的别名。

© www.soinside.com 2019 - 2024. All rights reserved.