MySQL Forums
Forum List  »  Newbie

How to write a query re-format results so one column becomes row headers with distinct results
Posted by: Gena Mak
Date: November 15, 2024 10:45AM

Hi,
This is my first encounter with MySQL8. I need help to write a pivot query to convert one row into columns and display data for each column. The number of foods in the table is dynamic but to display it on a screen I want to limit to 15. So, having 150 food items in food table would make it 10 tables as on the sample below. I am not just trying to aggregate totals as in some suggested examples. I need to format results as they are appear in actual table but, I need to reformat the results table in such a way that Description column would appear as distinct Description table headers with Nutrients in the first column with following [optional] amounts associated with the particular Description. If no amount is allocated for a particular combination of Description and Nutrient dash "-" is displayed.

Table DDL below:

CREATE TABLE food (
food_id int,
description text
);
CREATE TABLE food_nutrient (
food_id int,
nutrient_id int,
amount double
);
CREATE TABLE nutrient (
nutrient_id int DEFAULT NULL,
name text
);
insert into food(food_id, description)
values
(1, 'cookies'),
(2, 'coffee'),
(3, 'tea');

insert into nutrient(nutrient_id, name)
values
(10, 'vitamin b'),
(11, 'vitamin c'),
(12, 'water'),
(15, 'sugar');
(22, 'fatty acid'),
(33, 'sodium');

insert into food_nutrient(food_id, nutrient_id, amount)
values
(1, 11, 1),
(1, 12, 2),
(1, 33, 3),
(2, 12, 10),
(2, 33, 2),
(3, 12, 15),
(3, 15, 8);
select description, name, amount
from food f
join food_nutrient fn on fn.food_id = f.food_id
join nutrient n on n.nutrient_id = fn.nutrient_id

**The result of the query below**

Description | Name | Amount
---------------------------------------
cookies | vitamin c | 1
cookies | water | 2
cookies | sodium | 3
coffee | water | 10
coffee | sodium | 2
tea | water | 15
tea | sugar | 8

**I need this to look like this**

Nutrients | cookies | coffee | tea
----------------------------------------------------
vitamin c | 1 | - | -
vitamin b | - | - | -
fatty acid | - | - | -
sodium | 3 | 2 | -
water | 2 | 10 | 15
sugar | - | - | 8

Thank you in advance

Options: ReplyQuote


Subject
Written By
Posted
How to write a query re-format results so one column becomes row headers with distinct results
November 15, 2024 10:45AM


Sorry, only registered users may post in this forum.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.