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.
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.)
and simply join them with a Junction Table, referencing the previously mentioned above Primary Keys as Foreign Keys
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
Related
I need your help in one SQL Query for converting the example table given below. Where I need Facilities as columns.
Seasonid
Product
Facility
Price
Product Type
1
Socks
Montreal
24
Wool
2
Slippers
Mexico
50
Poly
3
Slippers
Montreal
27
Rubber
4
Socks
Mexico
24
Cotton
5
Socks
Montreal
26
Cotton
Below table is how I'm expecting it to look like
seasonid
Product
Montreal
Mexico
Product Type
1
Socks
24
0
Wool
2
Slippers
0
50
Poly
3
Slippers
27
0
Rubber
4
Socks
0
24
Cotton
5
Socks
26
0
Cotton
In the expected result table even though 5th row data can be accommodated in 4th row itself like
seasonid
Product
Montreal
Mexico
Product Type
4
Socks
26
24
Cotton
my requirement requires it in a different row.
I found some pivot examples online, but they only show averaging or summing up the values and won't add the rows to already existing columns and display them all. I couldn't find a relevant post for this question. Please let me know if there is any relevant post.
Is it possible with Sql in the first place? If yes, then how?
I think you're mistaken about the pivot part because there's no pivot happening here. This can be achieved with IF() or CASE expression functions added to a very basic MySQL syntax. So, this:
SELECT * FROM mytable;
Will return you all columns and rows. Then this:
SELECT Seasonid, Product, Facility, Price, ProductType
FROM mytable;
is basically the same as the query before-that will return all columns and rows. Only difference is here we're explicitly defining all the column names from the table. So, from here you only need to modify the Facility and Price part with conditional IF() or CASE() and define it twice in the SELECT section, like this:
SELECT seasonid,
Product,
CASE WHEN Facility='Montreal' THEN Price ELSE 0 END AS 'Montreal',
CASE WHEN Facility='Mexico' THEN Price ELSE 0 END AS 'Mexico',
ProductType
FROM mytable;
Or
SELECT seasonid,
Product,
IF(Facility='Montreal',Price,0) AS 'Montreal',
IF(Facility='Mexico',Price,0) AS 'Mexico',
ProductType
FROM mytable;
In which both queries are able to get your desired result.
Demo fiddle
I'm just learning PHP and MySQL and I have two tables in the same database : FirstYear , SecondYear that have a structure like this :
StudentId |Math | Physics StudentId1 | Math1 | physics1
Joe 10 14 Alan 12 17
Alan 13 17 Smith 11 13
Smith 9 9 Joe 10 15
Is it possible to write a query that select and compare the two columns StudentId , StudentId1 to find matched records and if for example Joe=Joe after that compare records of math with math1 and physics with physics1 that are in the same row as matched records of StudentId with StudentId1 ;the idea of this query is to study the improvement of same student from first year to the second one ,Thanks .
Yes, it is possible but you have to complete SQL fundamental course.
In this situation you have to know about JOIN. Such as, Inner Join, Left Join, Right Join, Full Join etc. Also, compare with unique id, not name. Because, name always duplicate. It is not good practice. So, Know about primary key and foreign key.
However,
Query-
SELECT * FROM FirstYear INNER JOIN SecondYear ON FirstYear.StudentId = SecondYear.StudentId1 WHERE FirstYear.id = 1
Something like that, alternatively, you can try to another logic.
First let me say that yes, this is a horrible way to have stored data, second, it isn't my fault :) I am trying to integrate with a 3rd party database to extract info which is stored in 3 tables, which really should have been in two AND stored where table 2 had a many to one relationship. Since that isn't the case, I have a puzzle to share.
Table one contains rows in which multiple values can be stored. Each row has codeid1-codeid20. These columns may contain a value, or a 0 (they are never null). They also have a corresponding codetype1-codetype20 which will be either 0 or 1.
If codetype1 is equal to 0, we go to table 2 and select description from the matching table1.codeid1=table2.id. If codetype1 equals 1, we now have to look at table3 and find where table1.codeid1=table3.id and then match table3.table2id=table2.id and return the description.
Here is the data structure:
table1
codeid1,codeid2,codeid3,...codeid20 ... codetype1,codetype2,codetype3,.....codetype20
18 13 1 33 0 0 1 1
13 21 45 0 0 1 0 0
table2
id, description
13 Item 13 Description
15 Item 15 Description
17 Item 17 Description
18 Item 18 Description
21 Item 21 Description
28 Item 28 Description
45 Item 45 Description
table3
id, table2id
1 15
33 17
21 28
The results I would be looking for would look like this:
rowid, description
1 Item 18 Description
1 Item 13 Description
1 Item 15 Description
1 Item 17 Description
2 Item 13 Description
2 Item 28 Description
2 Item 45 Description
I got started working with someone last night, but I had missed part of the complexity of my situation in not integrating table3. Like I said, fun puzzle... This gives me the relationship between the first 2 tables, but I am unsure how I can work in a 3rd table.
SELECT table1.rowid, table2.description
FROM table2
INNER JOIN table1
ON table2.id=table1.codeie1
OR table2.id=table1.codeie2
...
The database is a Faircom C-Tree DB over an ODBC connection, which is generally compatible with Mysql statements including UNION, WITH, INTERSECT, EXISTS, JOIN... There is no PIVOT function.
https://docs.faircom.com/doc/sqlref/sqlref.pdf
Perhaps it will work with or rather than in:
where exists (select 1
from table1 as t1
where t2.id = t1.codeid1 or
t2.id = t2.codeid2 or
. . .
);
I am wondering if any of you would be able to help me. I am trying to loop through table 1 (which has duplicate values of the plant codes) and based on the unique plant codes, create a new record for the two other tables. For each unique Plant code I want to create a new row in the other two tables and regarding the non unique PtypeID I link any one of the PTypeID's for all inserts it doesnt matter which I choose and for the rest of the fields like name etc. I would like to set those myself, I am just stuck on the logic of how to insert based on looping through a certain table and adding to another. So here is the data:
Table 1
PlantCode PlantID PTypeID
MEX 1 10
USA 2 11
USA 2 12
AUS 3 13
CHL 4 14
Table 2
PTypeID PtypeName PRID
123 Supplier 1
23 General 2
45 Customer 3
90 Broker 4
90 Broker 5
Table 3
PCreatedDate PRID PRName
2005-03-21 14:44:27.157 1 Classification
2005-03-29 00:00:00.000 2 Follow Up
2005-04-13 09:27:17.720 3 Step 1
2005-04-13 10:31:37.680 4 Step 2
2005-04-13 10:32:17.663 5 General Process
Any help at all would be greatly appreciated
I'm unclear on what relationship there is between Table 1 and either of the other two, so this is going to be a bit general.
First, there are two options and both require a select statement to get the unique values of PlantCode out of table1, along with one of the PTypeId's associated with it, so let's do that:
select PlantCode, min(PTypeId)
from table1
group by PlantCode;
This gets the lowest valued PTypeId associated with the PlantCode. You could use max(PTypeId) instead which gets the highest value if you wanted: for 'USA' min will give you 11 and max will give you 12.
Having selected that data you can either write some code (C#, C++, java, whatever) to read through the results row by row and insert new data into table2 and table3. I'm not going to show that, but I'll show how the do it using pure SQL.
insert into table2 (PTypeId, PTypeName, PRID)
select PTypeId, 'YourChoiceOfName', 24 -- set PRID to 24 for all
from
(
select PlantCode, min(PTypeId) as PTypeId
from table1
group by PlantCode
) x;
and follow that with a similar insert.... select... for table3.
Hope that helps.
Sorry for not many clear title.
1st table "place":
ID PLACE AREA_1 AREA_2 AREA_3
1 Mago 23 45 67
2 Gelato 23 45 12
And so on
2nd table "area_1"
ID ID_AREA_1 AREA_1
1 23 Lazio
3rd table "area_2"
ID ID_AREA_2 AREA_2
1 45 Roma
4th table "area_3"
ID ID_AREA_3 AREA_3
1 12 Roma
2 67 Velletri
Of course with 3 INNER JOIN I can extract in this mode
ID PLACE AREA_1_NAME AREA_2_NAME AREA_3_NAME
1 Mago Lazio Roma Velletri
But I need to re-factory the database, losing 2nd, 3rd and 4th table and I need to obtain a new, unique table directly with
ID PLACE AREA_1_NAME AREA_2_NAME AREA_3_NAME
1 Mago Lazio Roma Velletri
1) I need absolutely to mantain inalterate the ID (id of place) of the 1st table (are used in others tables that I will mantain)
2) I don't need anymore the 2nd, 3rd and 4th tables
Could you help me to create the SQL statement for MySQL to prattically move the result of the JOINS to a new table?
Thank you very, very much!