SQL查询询问问题

时间:2014-06-26 08:09:05

标签: 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”,“Tip inchidere”,“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"

1 个答案:

答案 0 :(得分:0)

也许是这样的:

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