I'm stuck with a problem in MySql, please help me.
In this example I have two tables, one with the results of a bunch of competitors and one that defines which three competitors that makes a team. In reality I have a number of other tables as well, but they are not really needed to describe this problem.
Table with results for each competitor
| competitor_id | result1 | result2 | result3 | result4 |
| 1 | 1 | 1 | 1 | 1 |
| 2 | 1 | 2 | 2 | 1 |
| 3 | 2 | 3 | 2 | 1 |
| 4 | 1 | 5 | 3 | 2 |
| 5 | 4 | 3 | 2 | 3 |
| 6 | 3 | 2 | 1 | 2 |
| 7 | 2 | 1 | 4 | 2 |
| 8 | 2 | 1 | 2 | 1 |
| 9 | 1 | 2 | 3 | 2 |
Table showing teams
| team_id | competitor1 | competitor3 | competitor3 |
| 1 | 1 | 3 | 4 |
| 2 | 2 | 8 | 9 |
| 3 | 7 | 6 | 5 |
I would now like to create a query that gives me the total sum of each team. I need to have it i one query (maybe with subqueries) because I need to sort desc on the total result.
In other words, I need a result set giving me team.id sorted desc on the total result of each team.
Anyone?
EDIT: Here's an update showing the desired result
First, let´s sum the results of each competitor:
Competitor 1: 1+1+1+1=4
Competitor 2: 1+2+2+1=6
Competitor 3: 2+3+2+1=8
Competitor 4: 1+5+3+2=11
Competitor 5: 4+3+2+3=12
Competitor 6: 3+2+1+2=8
Competitor 7: 2+1+4+2=9
Competitor 8: 2+1+2+1=6
Competitor 9: 1+2+3+2=8
Then let's look at the team table.
Team 1 consists of competitors 1, 3 and 4.
Team 2 consists of competitors 2, 8 and 9.
Team 3 consists of competitors 7, 6 and 5.
Total sum of team with id = 1 is 4+8+11=23
Total sum of team with id = 2 is 6+6+8=20
Total sum of team with id = 3 is 9+8+12=29
Given all of this, I would like my result set to be
| id | team_sum |
| 3 | 29 |
| 1 | 23 |
| 2 | 20 |
Why not redesign your database like you have only two tables one for competitors and one for team like :
Competitors Table:
`competitor_id`, `team_id`, `result1`, `result2`, `result3`, `result4`
Team Table:
`team_id`, `team_name`
And your query would be very easy like:
SELECT A.team_id, B.team_name, SUM(result1+result2+result3+result4) as TotalResult
FROM competitors A
INNER JOIN team B
ON A.team_id=B.team_id
GROUP BY A.team_id, B.team_name
See my fiddle demo
Related
Consider the following sample table from a soccer tournament (let's call this table matches)
+----------+---------+--------------+
| match_id | club_id | goals_scored |
+----------+---------+--------------+
| 1 | 1 | 1 |
| 1 | 2 | 0 |
| 2 | 1 | 1 |
| 2 | 3 | 1 |
| 3 | 1 | 0 |
| 3 | 4 | 2 |
| 4 | 2 | 2 |
| 4 | 3 | 4 |
| 5 | 2 | 4 |
| 5 | 4 | 0 |
| 6 | 3 | 1 |
| 6 | 4 | 1 |
+----------+---------+--------------+
The resulting table we want should give us each club's total goals scored AND goals conceded:
+---------+--------------+----------------+
| club_id | goals_scored | goals_conceded |
+---------+--------------+----------------+
| 1 | 2 | 4 |
| 2 | 6 | 4 |
| 3 | 6 | 4 |
| 4 | 3 | 5 |
+---------+--------------+----------------+
Getting goals scored is straight forward enough...
SELECT SUM(goals_scored),
club_id
FROM matches
GROUP BY club_id
but I am absolutely flummoxed as to how to get it for each team's opponents.
I could, of course, construct a pretty complex array of subqueries to get there. If this were application-side work I'd likely just stuff it in a loop and iterate over each club to get there, but my use case requires a SQL answer if possible. Any thoughts?
edit: also if anyone has any better ideas on how to title this question, I'm all ears - I'm not really sure exactly how to describe this problem in the first place.
We can use a self-join approach here:
SELECT
m1.club_id,
SUM(m1.goals_scored) AS goals_scored,
SUM(m2.goals_scored) AS goals_conceded
FROM matches m1
INNER JOIN matches m2
ON m2.match_id = m1.match_id AND
m2.club_id <> m1.club_id
GROUP BY
m1.club_id
ORDER BY
m1.club_id;
This approach brings the goals conceded by each club to the other club, for each match, into a single row. We then just aggregate by club to get the two sums.
I have a table with two teams and frag counts
| id | teamA_name | teamA_frags | teamB_name | teamB_frags |
| 1 | 5 | 3 | 7 | 9 |
| 2 | 5 | 4 | 7 | 1 |
| 3 | 3 | 2 | 6 | 4 |
| 4 | 3 | 8 | 6 | 8 |
Is it possible to sum up all frags and present this data like that?
| team | frags |
| 5 | 7 |
| 7 | 10 |
| 3 | 10 |
| 6 | 12 |
EDIT 1: I tried queries with group by and group concat, but they are not giving me the output I wanted. For example:
SELECT teamA_name, teamB_name, SUM(teamA_frags), SUM(teamB_frags) FROM Table;
This is summing up frags OK, but printing teams next to eachother. My knowledge of SQL is limited.
Basically, you need to unpivot and re-aggregate. Here is one approach:
select team, sum(frags)
from ((select teamA_name as team, teamA_frags as frags
from t
) union all
(select teamB_name as team, teamB_frags as frags
from t
)
) t
group by team;
It's me again with my weird queries.
table users:
id | type | partner | company
------------------------------
1 | 2 | 0 | comp1
2 | 3 | 2 | comp2
3 | 3 | 2 | comp3
4 | 3 | 3 | comp4
table orders:
id | user | partner
--------------------
1 | 2 | 2
2 | 2 | 2
3 | 2 | 3
4 | 3 | 2
I know it's a little hart to keep track of all these numbers.
I'm logged in as type 2(users table) and want to get listed all information from the orders table from the users with type 3 and which are listed as my partners (partner 2) in addition I want the company name from the users table also in my results.
The query will be excecuted on the orders table.
result:
id | user | partner | company
------------------------------
1 | 2 | 2 | comp2
2 | 2 | 2 | comp2
4 | 3 | 2 | comp3
Thanks in advance and ask me if you don't understand the problem. I will try to explain better and any edits to make it more clear are also welcomed.
Perhaps this
select s.id,
case when src = 'u' then s.users
else s.partner
end as users,
case when src = 'p' then s.users
else s.partner
end as partner,
u.company
from
(
select 'u' as src,id,users,partner from o where users = 2 and (users = partner)
union
select 'p',id,partner,users from o where partner = 2 and (users <> partner)
) s
join u on u.id = s.partner
where type = 3;
Hopefully self explanatory, note I only need to know the user, the query figures out the partners.
result
+------+-------+---------+---------+
| id | users | partner | company |
+------+-------+---------+---------+
| 2 | 2 | 2 | comp2 |
| 1 | 2 | 2 | comp2 |
| 4 | 3 | 2 | comp3 |
+------+-------+---------+---------+
3 rows in set (0.00 sec)
I'm kinda lost on what kind of SQL query I should do to achieve what I want.
Let's say I have three tables :
select * FROM trip;
| trip_id | title | description
----------------------------------
| 1 | title1 | desc1 |
| 2 | title2 | desc2 |
| 3 | title3 | desc3 |
| 4 | title4 | desc4 |
| 5 | title5 | desc5 |
| 6 | title6 | desc6 |
select * FROM weekly_report;
| report_id | trip_id| incident_id
----------------------------------
| 1 | 1 | (null) |
| 2 | 1 | (null) |
| 3 | 1 | 1 |
| 4 | 2 | 2 |
| 5 | 3 | 3 |
| 6 | 3 | (null) |
select * FROM incident;
| incident_id | error_code |
----------------------------------
| 1 | 22223 |
| 2 | 25456 |
| 3 | 25456 |
So for a little operationnal knowledge :
The trip table contains 1 record PER trip done by the customer.
The weekly_report contains A report per Week of the trip. (1 trip of 2 weeks will have 2 records, 1 trip or 5 weeks will have 5.. ).
The incident table contains 1 record per incident. (If an incident happened during a week : we create a record in the incident table, else we do nothing)
I'd like to find in a single query (or if it has to be, with subqueries) the number of trips where during at least a week there has been an incident declared for the error_code "25456".
Expected result from the sample data : 2 ( because for trip 2 and three there exist an incident with the error code 25456 ).
I can explain more if needed, is there anybody out there willing to help me ?
Thanks,
You need to take count of distinct trips for related incidents
select count(distinct w.trip_id)
from weekly_report w
inner join incident i
on w.incident_id = i.incident_id
where i.error_code = 25456;
Try this:
SELECT w.trip_id
FROM incident i
INNER JOIN weekly_report w ON i.incident_id=w.incident_id
WHERE error_code='25456'
and if you want the count,then
SELECT COUNT(w.trip_id)
FROM incident i
INNER JOIN weekly_report w ON i.incident_id=w.incident_id
WHERE error_code='25456'
I had a technical interview last week, and my interviewer asked me what happens if I run the following query:
SELECT * FROM tbl1, tbl2
I think I answered it correctly, but it wasn't an in-depth answer.
I said that I would select all the columns in both tables. For example if tbl1 has 3 columns, and tbl2 has 4 columns. The result set would have 7 columns.
Then he asked me why 7? and I said because I was selecting everything from each table.
That was a bad answer, but I couldn't think of anything else.
To cut to the chase, after the interviewed I executed the latter statement using two tables.
Table A, had 3 animal: dog, cat and elephant.
Table B had 2 names: Mat and Beth
This is the result set that I got after the statement being executed:
*********************************************
| id_tbl1 | name_tbl1 | id_tbl2 | name_tbl2 |
*********************************************
| 1 | dog | 1 | Mat |
| 2 | cat | 1 | Mat |
| 3 | elephant | 1 | Mat |
| 1 | dog | 2 | Beth |
| 2 | cat | 2 | Beth |
| 3 | elephant | 2 | Beth |
*********************************************
So my question is, why does the statement behaves like that?
In other words:
Why does the Table B's records repeat themselves until I reach the end of table A, and then it starts all over again?
How would you have answered the question in a way that it would've "WOW'd" the interviewer?
If this question does not belong to SO, feel free to delete it or close it!
If you do a select like this, all rows in one resultset are joined to all rows in the other resultset (Cartesian Product).
So you get a list of all rows of the first table with the first row of the second table, Then all entries for the second row and so on. The order may be an implementation detail. Not sure if it is defined that the first order is by the first table, it might be different across implementations.
If you join three tables (or more), then the same happens with all rows of all tables. This, of course, is not only for tables, but for any result set from joins.
The result will be a cartisian product
take a look at this example
SQL Example
You can see there are two tables one has 5 records and the other has 4 and the result is 20 records. Means 5 * 4 = 20 instead of 5 + 4 = 9 as you are assuming.
Table1
| IDX | VAL |
---------------
| 1 | 1val1 |
| 1 | 1val2 |
| 2 | 2val1 |
| 2 | 2val2 |
| 2 | 2val3 |
Table2
| ID | POINTS |
---------------
| 1 | 2 |
| 2 | 10 |
| 3 | 21 |
| 4 | 29 |
Result of below query
SELECT * FROM Table1 , Table2
| IDX | VAL | ID | POINTS |
-----------------------------
| 1 | 1val1 | 1 | 2 |
| 1 | 1val1 | 2 | 10 |
| 1 | 1val1 | 3 | 21 |
| 1 | 1val1 | 4 | 29 |
| 1 | 1val2 | 1 | 2 |
| 1 | 1val2 | 2 | 10 |
| 1 | 1val2 | 3 | 21 |
| 1 | 1val2 | 4 | 29 |
| 2 | 2val1 | 1 | 2 |
| 2 | 2val1 | 2 | 10 |
| 2 | 2val1 | 3 | 21 |
| 2 | 2val1 | 4 | 29 |
| 2 | 2val2 | 1 | 2 |
| 2 | 2val2 | 2 | 10 |
| 2 | 2val2 | 3 | 21 |
| 2 | 2val2 | 4 | 29 |
| 2 | 2val3 | 1 | 2 |
| 2 | 2val3 | 2 | 10 |
| 2 | 2val3 | 3 | 21 |
| 2 | 2val3 | 4 | 29 |
I think you are confusing yourself by running an example with two tables that have identical fields. You are referring to a Union, which will combine the values of 1 table with another, and using your example this would give you 3 + 4 = 7 results.
The comma separated FROM statement is doing JOIN, which will go through all values in Table X and pair them with all the values of Table Y. This would result in Size of X * Size of Y results, and using your example this would be 3 * 4 = 12.