I'm trying to learn SQL, and while I'm slowly learning how to query data, I'm stuck on querying the results of a query. Take this example
I want an SQL statement to do 2 things. Suppose I have 2 tables like the one below (table 1 borrowed from another example on stack overflow)
Table 1:
ID game point time
1 x 5 7:00
1 z 4 11:00
2 y 6 9:00
3 x 2 2:00
3 y 5 4:00
3 z 8 6:00
4 k 0 8:00
Table 2:
id tv chan
1 cab
2 trop
3 start
4 cab
The first thing I want to do is combine certain columns from these tables. I know I can select these columns and do an inner join on ID
However the second thing I want to do is drop all the rows with point value 0, and then have only rows with distinct game name with the lowest point value. So I want the final table to look like this
id game point tv chan
1 z 4 cab
2 y 5 trop
3 x 2 start
Thanks
You could try something like this:
SELECT t1.ID,
t1.game,
t1.point,
t2.tv_chan
FROM Table1 AS t1
INNER JOIN Table2 AS t2 ON t2.id = t1.id
INNER JOIN (SELECT t11.game, MIN(t11.point) AS min_point
FROM Table1 AS t11
WHERE t11.point != 0
GROUP BY t11.game
) AS t3 ON t3.game = t1.game
AND t3.min_point = t1.point
WHERE t1.point != 0
You could use a join with a subquery that group by id and game for obtain the min point
select t1.id, t1.game. t1.point, t2 `tv chan`
from (
select id, game, min(point) point
from table1
where point > 0
group by id, game
) t1
inner join table2 t2 on t1.id = t2.id
Related
T1
SCHOOL STUDENT TEACHER
1 1 A
1 2 B
1 3 B
1 4 B
T2
SCHOOL STUDENT TEACHER
2 7 A
2 6 A
2 8 B
2 9 B
T3
SCHOOL TEACHER ID
1 A FOX
1 B CAT
2 A DOG
2 B MOUSE
T4
SCHOOL STUDENT TEACHER ID
1 1 A FOX
1 2 B CAT
1 3 B CAT
1 4 B CAT
2 7 A DOG
2 6 A DOG
2 8 B MOUSE
2 9 B MOUSE
I have T1 T2 T3 where I wish to UNION T1 and T2 and afterwards JOIN T3 such as:
SELECT * FROM T1
UNION
(SELECT * FROM T2)
JOIN
(SELECT SCHOOL, TEACHER, ID
WHERE SCHOOL != 10
FROM T3)
BUT I receive error "UNEXPECTED JOIN"
JOIN is a part of a SELECT statement while UNION are not.
So, you need to make UNION as a part of a SELECT statement
select * from (
SELECT * FROM T1
UNION
SELECT * FROM T2) q1
JOIN
(SELECT SCHOOL, TEACHER, ID
FROM T3
WHERE SCHOOL != 10) q2
on /* here goes JOIN condition you need, like q1.school = q2.school*/
Please note:
there is another syntax error in your example: FROM goes always after SELECT and before WHERE
UNION will append result and eliminate duplicate rows which can run slower than UNION ALL. The latter will not check whether there are duplicate rows. So, if you're sure there won't be any duplicates in the result or if it's irrelevant whether you get duplicates or not, you may use UNION ALL
My tables look something like this
table 1 :
relid BID
1 1
1 2
1 3
table 2:
id BID priority info
1 1 0 Json string
2 1 1 **
3 1 2 ****
4 2 0 ***
5 2 1 ****
6 3 0 ****
the question is that I want to select all the BID's with only the highest priority from table2 using inner join with table1, which means I want to get this result
id BID Priority info
3 1 2 Json String info
5 2 1 ***
6 3 0 ***
I've used this query and it works fine but with large numbers of records it works too slow !! the fetching time may last up to 70 seconds in MySQL which is a disaster for my server !!!
select * from table1 inner join table2 on table1.BID = table2.BID where table1.relid = 1 and table2.priority = (select max(priority) as m from table2 where table1.BID = table2.BID)
anyone has other suggestions that might work with better performance!
Consider the following:
SELECT y.id
, y.bid
, y.priority
, y.info
FROM table1 x
JOIN table2 y
ON x.BID = y.BID
JOIN (SELECT bid, MAX(priority) max_priority from table2 GROUP BY bid) z
ON z.bid = y.bid
AND z.max_priority = y.priority
WHERE x.relid = 1;
For further improvements, we'd really need to see proper CREATE TABLE statements for all relevant tables as well as the result of the EXPLAIN
I have 2 tables in Mysql. I need to join them somehow to get one value from second table into the first one.
TABLE 1
Day EmployeeId Total EmployeeName
1 2 20 Josh
1 1 20 Mike
2 2 5 Josh
2 1 10 Mike
3 3 5 Eric
TABLE 2
Day EmployeeId Max_Total
1 2 40
1 1 40
2 2 5
2 1 15
I need to get something like TABLE 3
Day EmployeeId Total EmployeeName Max_Total
1 2 20 Josh 40
1 1 20 Mike 40
2 2 5 Josh 5
2 1 10 Mike 15
3 3 5 Eric null
So this Max_Total column needs to be somehow created and populated.
This Day_EmployedId combination is unique in both tables and that should be used somehow to extract values from 2nd table and add it to the first one.
Sometimes first table can have more values, sometimes the second one, but the first one will always be the one that needs to be manipulated/added to.
Any hint will be appreciated. Thanks
You are looking for a left join on two fields:
select t1.*, t2.max_total
from table1 t1 left join
table2 t2
on t1.day = t2.day and t1.employeeid = t2.employeeid;
I would not recommend actually updating table1. You can generate the data as you need it. However, in order for an update to work, you need to add a column to the table first, and then update it.
You need to separate your tasks.
Alter your Table1 to add the column Max_Total
Write UPDATE query to update your Max_Total in your Table1.
Query:
UPDATE t1.Max_Total = t2.Max_Total
SET t1.
FROM Table1 t1
JOIN Table2 t2 ON t1.Day = t2.Day AND t1.EmployeeId = t2.EmployeeId
If you are only concerned about getting a combined result set
SELECT t1.Day, t1.EmployeeId, t1.Total, t1.EmployeeName, t2.Max_Total
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.Day = t2.Day AND t1.EmployeeId = t2.EmployeeId
For more information on LEFT JOIN, you can study this tutorial.
How can i edit the ON operator part of my query below such that i would like the current code to work where id<4 (which is t2.id <= t1.id as shown below) so when t1 id=3, t2 is the cumulative id from id=1 to id=3 (as it is now).
but for id >3 I would like the ON operator to be (t2.id=t1.id>=t1.id-2 and <=t1.id) so when t1 id=4, t2.id should be between 2 and 4 inclusive. when t1 id =5, t2.id should be between 3 and 5 inclusive and so on.
I'm doing this because when i calculate col E for ids after id=3, i am only interested in getting the average of the previous 2 rows for C and D on a moving average.
Iam translating my excel formula into SQL so i know what is the correct values for col E.
My query has 2 sub queries and it updates column E. The table and correct data in EXCEL looks like this:
id A B C D E
1 NULL NULL NULL NULL NULL
2 4 6 1 1 1
3 6 9 1.2 1.2 1.2
4 8 7 1.33 0.954 1.143
5 10 5 1.25 0.714 0.982
6 12 2 1.2 0.428 0.814
http://www.sqlfiddle.com/#!2/17a0ad/1
EXCEL formulas (notice that the formulas change after id=3 to a moving average):
id C D E
2 =A2/AVERAGE(A1:A2) =B2/AVERAGE(B1:B2) =(C2+D2)/2
3 =A3/AVERAGE(A1:A3) =B3/AVERAGE(B1:B3) =(C3+D3)/2
4 =A4/AVERAGE(A2:A4) =B4/AVERAGE(B2:B4) =(C4+D4)/2
5 =A5/AVERAGE(A3:A5) =B5/AVERAGE(B3:B5) =(C5+D5)/2
6 =A6/AVERAGE(A4:A6) =B6/AVERAGE(B4:B6) =(C6+D6)/2
Here is my SQL query:
Update followers join
(
SELECT t1.id ,ifnull(t1.A/AVG(t2.A),null) C ,ifnull(t1.B/AVG(t2.B),null) D
FROM followers t1
JOIN followers t2
ON
case when t2.id < 4 then t2.id <= t1.id else t2.id<= t1.id and t2.id>=t1.id-2 end
group by t1.id
) AS tt on(followers.id = tt.id)
SET E = (tt.C + tt.D)/2;
Although this query works, the numbers that i want for col E are not exactly correct. They are correct only for id<=4 but not for id=5 or id=6 in col E.
I believe my syntax for CASE by the ON operator might be wrong.
I ran this query in sql fiddle and got this result:
ID A B E
1(null)(null)(null)
2 4 6 1
3 6 9 1.2
4 8 7 1.14
5 10 5 1.08
6 12 2 0.92
As we can see, the excel and sql output are different.
Thanks,
I think the query that you want is a very slight modification:
Update followers join
(SELECT t1.id, ifnull(t1.A/AVG(t2.A),null) as C, ifnull(t1.B/AVG(t2.B),null) as D
FROM followers t1 JOIN
followers t2
ON (case when t1.id < 4 then t2.id <= t1.id
----------------------------^
else t2.id<= t1.id and t2.id>=t1.id-2
end)
group by t1.id
) tt
on followers.id = tt.id
SET E = (tt.C + tt.D)/2;
You can express the on using basic boolean logic as:
on t2.id <= t1.id and (t1.id < 4 or t2.id >= t1.id - 2)
i have two tables as follows------
table-1
CalenderType periodNumber periodstartdate
1 1 01-01-2013
1 2 11-01-2013
1 3 15-01-2013
1 4 25-01-2013
2 1 01-01-2013
2 2 15-01-2013
2 3 20-01-2013
2 4 25-01-2013
table2
Incidents Date
xyz 02-01-2013
xxyyzz 03-01-2013
ccvvb 12-01-2013
vvfg 16-01-2013
x3 17-01-2013
x5 24-01-2013
Now i want to find out the number of incidents took place in a given period(the Calendar type may change on runtime like)
the query should look something like this
select .......
from ......
where CalendarType=1
which should return
CalendarType PeriodNumber Incidents
1 1 2
1 2 1
1 3 3
1 4 0
can someone suggest me an approach or any method how this can be achieved.
Note:each period is variable in size.peroid1 may have 10 days period2 may have 5 days etc.
I think this does what you want, although I don't understand how you arrived at your sample output:
select t.CalenderType, t.periodNumber, count(*) as Incidents
from Table1 t
inner join (
select t2.Date, t2.Incidents, max(t1.periodstartdate) as PeriodStartDate
from Table2 t2
inner join Table1 t1 on t2.Date >= t1.periodstartdate
where CalenderType = 1
group by t2.Date, t2.Incidents
) a on t.periodstartdate = a.PeriodStartDate
where CalenderType=1
group by t.CalenderType, t.periodNumber
SQL Fiddle Example
Try this, a bit more general solution,SQLFiddle (Thanks RedFilter for schema):
SELECT t1.CalenderType, t1.periodNumber, count(Incidents)
FROM Table1 t1, Table1 t11, Table2
WHERE
(
(
t1.CalenderType = t11.CalenderType
AND t1.periodNumber = t11.periodNumber - 1
AND Date BETWEEN t1.periodstartdate AND t11.periodstartdate
)
OR
(
t1.periodNumber = (SELECT MAX(periodNumber) FROM Table1 WHERE t1.CalenderType = CalenderType)
AND Date > t1.periodstartdate
)
)
GROUP BY t1.CalenderType, t1.periodNumber
ORDER BY t1.CalenderType, t1.periodNumber