SQL get column values from existing values

Viewed 35

I have a table like

Col 1. Col 2 Col 3
Apple 2021
Pears 2021
Apple 2020 2
Pears 2020 207
Banana 2017 272

I want to fill Col 3 where col 1 have same values

Col 1. Col 2 Col 3
Apple 2021 2
Pears 2021 207
Apple 2020 2
Pears 2020 207
Banana 2017 272

I tried self join but that's not working.. Any way I could get this result.

1 Answers

This is bad practice, assuming you're working with a SQL database. It is unnecessarily complex and generally a waste of storage space. Not to mention, if you want to change something, you'd have to do it multiple times (like you're currently doing, right now.)

Why don't you instead try normalization?

This is a resource for you to start - https://www.w3schools.in/dbms/database-normalization

For example -

Build 2 separate tables for the two entities; in this case, dates and fruits with corresponding Primary Keys (Date_Id and Fruit_Id respectively.)

dates table fruits table

and simply join them with a Junction Table, referencing the previously mentioned above Primary Keys as Foreign Keys

junction table

If you want to see a full table, ̷n̷o̷t̷ ̷s̷o̷ simply use the JOIN Keyword.

for reference - https://www.w3schools.com/sql/sql_join.asp and https://learnsql.com/blog/how-to-join-3-tables-or-more-in-sql/

example -

SELECT
  Fruits.Fruit_Name,
  Fruits.Fruit_Amount,
  Dates.Date_Value
FROM Fruits
JOIN Junction_Table
  ON Fruits.Fruit_Id = Junction_Table.Fruit_Id
JOIN Dates
  ON Dates.Date_Id = Junction_Table.Date_Id;

Would produce

enter image description here

Related