mysql - SQL查询询问问题

标签 mysql sql pivot-table

这是我的查询:

SELECT f.FieldID,fd.FieldName, p.ProductID,pd.ProductName, p.Price,p.Stoc, p.IsActive,TextValue
FROM products_products p
LEFT OUTER JOIN products_products_details pd
on pd.ProductID = p.ProductID
LEFT OUTER JOIN fld_chosenvalues f
on f.ProductID = p.ProductID
INNER JOIN fld_fields_details fd
ON f.FieldID = fd.FieldID
WHERE  pd.Locale = "ro-RO" and fd.Locale = "ro-RO"

在下图中,您可以看到查询结果: enter image description here

问题是我想将“Volum”、“Tipinchidere”、“Amabalare paiet”、“Ambalare bax”作为一列,并为其指定值“212ml”... 你可以在下图中看到我到底想要什么:

enter image description here

我对这些图像表示歉意,但我不知道有任何其他方法可以解释这一点。谢谢

这是带有数据透视表的查询,显然不起作用:

SELECT f.FieldID,fd.FieldName, p.ProductID,pd.ProductName, p.Price,p.Stoc, p.IsActive,TextValue
FROM products_products p
LEFT OUTER JOIN products_products_details pd
on pd.ProductID = p.ProductID
LEFT OUTER JOIN fld_chosenvalues f
on f.ProductID = p.ProductID
INNER JOIN fld_fields_details fd
ON f.FieldID = fd.FIeldID
PIVOT
(
    FOR [f.FieldName] IN (['Volum'], ['Tip inchidere'], ['Amabalare palet'], ['Ambalare bax'])
) as pvt;
WHERE  pd.Locale = "ro-RO" and fd.Locale = "ro-RO"

最佳答案

也许是这样的:

SELECT 
    p.ProductID,
    pd.ProductName,
    SUM(p.Price) AS Price,
    SUM(p.Stoc) AS Stoc,
    p.IsActive,
    MAX(CASE WHEN fd.FieldName='Volum' THEN TextValue ELSE NULL END) AS Volum,
    MAX(CASE WHEN fd.FieldName='Tip inchidere' THEN TextValue ELSE NULL END) AS TipInchidere,  
    MAX(CASE WHEN fd.FieldName='Amabalare paiet' THEN TextValue ELSE NULL END) AS AmabalarePaiet,
    MAX(CASE WHEN fd.FieldName='Ambalare bax' THEN TextValue ELSE NULL END) AS Ambalarebax
FROM 
    products_products p
    LEFT JOIN products_products_details pd
        on pd.ProductID = p.ProductID
    LEFT JOIN fld_chosenvalues f
        on f.ProductID = p.ProductID
    INNER JOIN fld_fields_details fd
        ON f.FieldID = fd.FieldID
WHERE  
    pd.Locale = 'ro-RO' 
    and fd.Locale = 'ro-RO'
GROUP BY
    p.ProductID,
    pd.ProductName,
    p.IsActive

关于mysql - SQL查询询问问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24425475/

相关文章:

php - 我是否需要编写代码来对来自 iOS 应用程序的服务器请求进行排队?

Php脚本不检查mysql表中的用户名值

mysql - 将列转换为行并创建新列?

python - 索引错误 : index 1491188345 is out of bounds for axis 0 with size 1491089723

php - 这个 mysql 查询出了什么问题?

mysql - 使用nodeJs和 'Q'异步连接到MySQL

mysql - 在桌面上管理 MySQL?

sql - 使用 int8range 连接 2 个大型 postgres 表不能很好地扩展

sql - 连接三张表,主表在中间

python - 旋转并重命名 Pandas 数据框