简体   繁体   中英

Displaying row values as column values in SQL

I am having this table in SQL(XAMP)

item_name         category_name        category_id
----------------------------------------------------
Flash_disk        Accessories          1    
Fanta             Food                 2    
Printer           Accessories          1    
Sprite             Food                2    

I am trying to display category_name column values as column values using this query and it displays very well as shown. sql:

SELECT category_id, MAX(IF(`category_name` = "Food", item_name, NULL)) Food, MAX(IF(`category_name` = "Accessories", item_name, NULL)) Accessories
FROM categories
GROUP BY category_id

and the results are

category_id         Food           Accessories
---------------------------------------------------
1                   NULL            Printer
2                   Sprite           NULL
---------------------------------------------------

Is there a way I can get all columns populated with values than displaying null values the results to be like this:

category_id         Food           Accessories
---------------------------------------------------
1                   Fanta          Printer
2                   Sprite         Flash_disk   
---------------------------------------------------

You could use coalesce() :

SELECT category_id,
       COALESCE(MAX(CASE WHEN `category_name` = 'Food' THEN  item_name END), 'Fanta') as Food, 
       COALESCE(MAX(CASE WHEN `category_name` = 'Accessories' THEN  item_name END), 'Flash_disk') as Accessories
FROM categories
GROUP BY category_id;

That expected result doesn't make much sense.

For example, why would Fanta have category_id 1 according those results?

But this query almost gets similar results:

SELECT rownum, 
MAX(CASE WHEN category_name = 'Food' THEN item_name END) AS Food, 
MAX(CASE WHEN category_name = 'Accessories' THEN item_name END) AS Accessories
FROM
(
    SELECT 
    MAX(cat1.category_name) AS category_name,
    COUNT(*) AS rownum,
    cat1.item_name
    FROM categories cat1
    JOIN categories cat2 ON cat2.category_id = cat1.category_id 
     AND cat2.item_name <= cat1.item_name
    GROUP BY cat1.category_id, cat1.item_name
) q
GROUP BY rownum
ORDER BY rownum;

Returns

rownum  Food    Accessories
1       Fanta   Flash_disk
2       Sprite  Printer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM