Rows in Columns

Asked

Viewed 49 times

3

I have the following result of a query:

NOMECARACTERISTICA      NOMEINFORMACAO
Marca                   Samsung
Marca                   ASUS
Modelo                  E32 370E4K-KW3
Modelo                  X555LF

My idea is to transform in the following form:

Marca       Modelo
Samsung     E32 370E4K-KW3    
ASUS        X555LF

I created the query down below:

SELECT 
    CASE WHEN NomeCaracteristica = 'Marca'  THEN NomeInformacao END AS Marca,
    CASE WHEN NomeCaracteristica = 'Modelo' THEN NomeInformacao END AS Modelo
FROM
(
    SELECT
       CAR.NomeCaracteristica AS NomeCaracteristica,
       INF.NomeInformacao AS NomeInformacao
    FROM
       caracteristica CAR INNER JOIN informacao INF ON CAR.IdCaracteristica = INF.IdCaracteristica 
    WHERE
       CAR.IdCategoria = 1 
    ORDER BY
       CAR.IdCaracteristica limit 4
) d

But it’s bringing me the result:

MARCA       Modelo
Samsung     NULL    
ASUS        NULL
NULL        E32 370E4K-KW3 
NULL        X555LF

Can someone help me get the result I need?

  • Which field links the brand to the model? There is some column missing in your question (to know if the Samsung is the X555LF or the E32 needs some equal field in both cases)

  • The problem is really the one that seems to have no association table between brand and model. You should then create a table that associates these two tables. Then you can make an INNER JOIN.

  • maybe this will help http://stackoverflow.com/questions/14834290/mysql-query-to-dynamically-convert-rows-to-columns

  • If there is no association table with PK and FK ai is difficult, otherwise it is possible to do creating a view.

  • Try using MAX before CASE with GROUP BY.

  • It was the same MAX I used. It already worked! Thanks!

Show 1 more comment

1 answer

0


sorry for the delay in feedback on this issue.

As it had been said by Bacco first, a column was missing in one of the tables to obtain this link.

That way, I was able to do the consultation I needed!

Thank you all!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.