5
I have a problem with a query, in which I need to turn rows into columns. In case I thought to use the function pivot, but it didn’t work very well, since mysql doesn’t provide me with such a function. But the tables are as follows::
My goal is to display the results as follows
However my query is a little awkward, because it returns the same products in different lines and ae can not display this way, even trying to group the columns.
SELECT pq.id_produto,pd.descricao,
CASE WHEN pl.id_loja = '1' THEN pq.produto_quantidade
END LOJA1,
CASE WHEN pl.id_loja = '2' THEN pq.produto_quantidade
END LOJA2,
CASE WHEN pl.id_loja = '3' THEN pq.produto_quantidade
END LOJA3,
CASE WHEN pl.id_loja = '4' THEN pq.produto_quantidade
END LOJA4
FROM pedidos_produtos_quantidade pq
LEFT JOIN pedidos_lojas pl ON pl.id = pq.id_pedido_loja
LEFT JOIN lojas l ON pl.id_loja = l.id
LEFT JOIN produtos pd ON pq.id_produto = pd.id_produto
GROUP BY pd.descricao,
pq.produto_quantidade
This sql generates this result, which I cannot group in the way I mentioned:
Someone could help me make this cluster?
Have you thought about using sub querys? It loses performance but in your case I think it fits well..
– Igor Monteiro
Actually mysql provides the pivot function yes, you would have to create a precedent.
– Ivan Ferrer
You have to use
SUM(pq.produto_quantidade) as LOJA1
to make the sum correctly.– Ivan Ferrer
something like:
IF(pl.id_loja = 1, SUM(pq.produto_quantidade), 0) as QUANT_LOJA1
.– Ivan Ferrer
Another thing, watch out for
left join
, for theleft join
brings everything that is similar in the second table... and in case you want to join some fields, then... for some cases, you should use theinner join
... look at that picture.– Ivan Ferrer
@Ivanferrer even with the IF and the sums the records are repedtidos, the Inner Join I entered and did not change the result
– tkmtts
@Igormonteiro may be that the subquery helps, but I still don’t know how to do it to give me a result next to the last image I sent
– tkmtts
tries to query the colleague below by playing the result in a temp table. After that it gives a group by in the columns you want to group by putting a sum.. I think it works
– Igor Monteiro