Apologies for the title but I am trying to do stuff way above my level even for me to explain it.
Say I have a table with the variables person, foodstuff and amount:
Person food Amount
Mike Butter 3
Mike Milk 4
Mike Chicken 2
Tim Milk 4
John Chicken 2
By joining the table with itself in the query I have managed to make a list where the food is the basis for new variables and the value is the amount. The above table would become:
Person Butter Milk Chicken
Mike 3 4 2
The code is approximately:
Select
a.person,
b.amount as Butter,
c.amount as Milk,
d.amount as Chicken
from PersonFoodAmount a
inner join PersonFoodAmount b on a.person = b.person
inner join PersonFoodAmount c on a.person=c.person
where b.food='Butter'
and c.food='Milk'
and d.food='Chicken'
Now, this gives me Mike because he checks all boxes off. But I need to also have the partial matches:
Person Butter Milk Chicken
Mike 3 4 2
Tim NULL 4 NULL
John NULL Null 2
I have tried all kinds of joins, including full outer join but I still only get persons with a full fridge.
Any suggestions?
Denormalization is a database optimization technique in which we add redundant data to one or more tables. This can help us avoid costly joins in a relational database. Note that denormalization does not mean 'reversing normalization' or 'not to normalize'.
Consequently, you can't be "over-normalized" or "under-normalized". Having said that, normalization has a performance cost. Some people elect to denormalize in various ways to improve performance. The most common sensible denormalization is to break 3NF and include derived data.
First Normal Form (1 NF) Second Normal Form (2 NF) Third Normal Form (3 NF) Boyce Codd Normal Form or Fourth Normal Form ( BCNF or 4 NF)
Normalization is the process to eliminate data redundancy and enhance data integrity in the table. Normalization also helps to organize the data in the database. It is a multi-step process that sets the data into tabular form and removes the duplicated data from the relational tables.
You can use Pivot for make this.
DECLARE @PersonStuff TABLE (Person varchar(10), Food varchar(10), Amount INT)
INSERT INTO @PersonStuff VALUES
('Mike','Butter', 3),
('Mike','Milk', 4),
('Mike','Chicken', 2),
('Tim','Milk', 4),
('John','Chicken', 2)
SELECT
*
FROM (
SELECT
*
FROM @PersonStuff ) AS SourceTable
PIVOT (
AVG(Amount)
FOR Food IN ( [Butter],[Milk],[Chicken] )
) AS PivotTable
Result:
Person Butter Milk Chicken
John NULL NULL 2
Mike 3 4 2
Tim NULL 4 NULL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With