Why is my average query showing incorrect values? [closed] - mysql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I asked a question a few hours ago that was marked as closed and referred me a link that did not clear up my confusion.
I am trying to query a sports database in MySQL to list the names of players who are above average age compared to their teammates. Ideally, I want to group by team, find the average of each team, and compare that to each respective player on that team.
My results from this query seem to be comparing players to the entire databases' average, rather than the average of the team. Can anyone correct my query or propose an alternate query to get the correct data? A friend of mine suggested perhaps using two copies of the tables, but that is beyond the scope of my limited MySQL skills.
My relational schema are as follows:
player(player_name, age, position)
plays_for (player_name, team_name)
SELECT player.player_name, player.age
FROM
plays_for
INNER JOIN player ON player.player_name=plays_for.player_name
WHERE (SELECT AVG(age) FROM player
GROUP BY plays_for.team_name1)< player.age

Your WHERE statement does not include the team grouping. I personally like WITH statements which seems to be the direction your friend was going.
> WITH average_ages AS ( SELECT AVG(p.age) AS average_age, pf.team_name
> FROM player p join plays_for pf on p.player_name = pf.player_name
> GROUP BY pf.team_name) aa
> SELECT player.player_name, player.age
> FROM plays_for
> INNER JOIN player ON player.player_name=plays_for.player_name
> INNER JOIN average_ages ON plays_for.team_name = average_ages.team_name
> WHERE player.age > average_ages.average_age;
The WITH statement at the top creates a temporary table of average ages and then joins it to the plays_for table.
The first few rows of the entire SELECT query before the WHERE statement would look like this
Name Age Team Average_age
Tara 51 KOs 25
Bomb 45 KOs 25
Jess 20 BES 30
Buster 40 BES 30

Related

Finding First Instance of Multiple Variable in Single Column in SQL [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
I've been trying to write some queries and subqueries but have struggled with one in particular.
Using the database at the below link, I am trying to find a way to separate multiple variables from a single column in to two.
https://www.w3resource.com/sql-exercises/soccer-database-exercise/subqueries-exercises-on-soccer-database.php
I can return the first match with a player scoring a goal from a penalty
`
SELECT a.player_id,MIN(b.play_date) AS firstmatchscoringpenalty FROM goal_details a
JOIN match_mast b ON a.match_no = b.match_no
WHERE a.goal_type = 'P'
GROUP BY a.player_id`
Player_ID
Firstmatchscoringpenalty
160333
2016-06-26
160235
2016-07-03
and the first match in which a player scored a "normal" goal`
`SELECT a.player_id,MIN(b.play_date) AS firstmatchscoringnormal FROM goal_details a
JOIN match_mast b ON a.match_no = b.match_no
WHERE a.goal_type = 'N'
GROUP BY a.player_id`
Player_ID
firstmatchscoringnormal
160236
2016-06-27
160316
2016-07-01
I would, however, like to return a result for all players who scored both a penalty and normal goal that includes both results across three columns, so something like:
Player_ID
Firstmatchscoringpenalty
firstmatchscoringnormal
Cell 1
Cell 2
Cell 3
Cell 4
Cell 5
Cell 6
Any ideas on how to do this would be much appreciated.

Mysql query with pivot table and multiple joins [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a sales table, a sale_staff table, a staff table and an offices table.
We are selling properties, and I want to find out the numbers of sales per seller for X month and per office.
The pivot table looks like this
sale_id , staff_id , type
type can be either seller or lister, so I need a where clause for this.
The sales table has a FK to the offices table; office_id
What I have so far is this, its TOTALLY wrong I know, but that's why i'm here - i need to fix the sums and include the office name from the office table, so
select st.first_name, st.last_name, office, count(*) as sold
from sales s, sale_staff ss
left join staff st
on st.id = ss.staff_id
left join offices off
on off.id = s.office_id
where ss.`type` = 'lister' and
year(s.sale_date) = 2017 and
month(s.sale_date) = 12
group by st.id
Sales table is simply a property sale item, price, address, office_id.
Besides the error unknown column s.office_id, as I said, the sum value is incorrect anyway. I'm really not experienced enough to understand this level of relationship joins and aggregating, any pointers please.
Basically I would like to simply see a resultset like
staff(seller) , count , office
Mike , 12 , West
Jim , 7 , East
Fred , 3 , East
Edit: SQLFiddle in case that helps :) Will add some sample test data.
Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. Your problem is because of the scoping rules around commas.
I would recommend:
select st.first_name, st.last_name, o.office, count(*) as sold
from staff st left join
sale_staff ss
on st.id = ss.staff_id join
sales sa
on sa.sale_id = ss.sale_id join
offices o
on o.id = s.office_id
where ss.`type` = 'lister' and
s.sale_date >= '2017-12-01' and
s.sale_date < '2018-01-01'
group by st.first_name, st.last_name, o.office;
I think this has the join condition correctly laid out, but it is hard to be sure without sample data and desired results.
Notes:
left join is probably not necessary. If it is, you should probably be starting with the staff table (to keep all staff).
Qualify all column names.
The group by includes all the non-aggregated columns in the from. This is a good habit if you are learning SQL.
The date comparisons are direct, without the use of functions.

How can display only the non minimum queries and exclude the minimum query [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a list of skill ratings
john - 6.2
lucy - 4.3
nikki - 5.7
selena - 7.1
I just want to exclude lucy as hers is the least rating and order the rest by descending order wrt rating, and i dont know the total number of people in the list, so the limit function is not gonna work.
Any help, noob alert
A more general answer than the accepted one would be to use LIMIT and OFFSET to remove any number of highest or lowest ranking rows. Then use another subquery to impose any ordering we want. Something like this:
SELECT *
FROM
(
SELECT *
FROM yourTable
ORDER BY rating
LIMIT 1000000000 OFFSET 1 --skips the lowest rating, but
) t -- we could skip any number of ratings
ORDER BY rating DESC;
Demo
You can use subqueries
First use the inner query to find out the minimum rating then exclude the rating
SELECT *
FROM table
WHERE rating NOT IN (SELECT MIN(rating)
FROM table)
ORDER BY rating DESC

Nobel prize winner database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have the Nobel prize winners database since the year it was first awarded. The source of the data is : http://www.aggdata.com/awards/nobel_prize_winners
It has one single table, so there is no foreign key nor any ER.
The table has following 12 columns: Id, Year, Category, Name, Birthdate, Birth Place, County, Residence, Role/Affiliate, Field/Language, Prize Name, Motivation.
Obviously there are multiple winners for categories such as physics, medicine etc.
I have been trying to see the number of Nobel prize winners per category per decade using query. I want my result table to look like:
______________________________________________
1960-1969 Peace 9 winners
1960-1969 Physics 19 winners
..............................................
1970-1979 Peace 6 winners
1960-1969 Physics 12 winners
..............................................
______________________________________________
Can this be possible through a query in MySQL?
Much appreciate your attention. Thank you all/
Here is a more SQL way to do this:
select concat(floor(npw.year / 10)*10, '-', floor(npw.year / 10)*10+9) as decade,
npw.category,
count(*) as winners
from NobelPriceWinners npw
group by floor(npw.year / 10), npw.category
order by decade, category;
This produces three columns as:
Decade Category Winners
1960-1969 Peace 9
1960-1969 Physics 19
. . .
Here's some ideas:
Assuming you want to represent the decade as xxx0-xxx9, and assuming the award_date is DATE datatype, you can use an expression to get first three characters of year:
SUBSTR(DATE_FORMAT(t.award_date,'%Y'),1,3)
A query something like this may get you started.
SELECT CONCAT(s.ccy,'0-',s.ccy,'9') AS decade
, s.category
, CONCAT(s.count_winners,' winners') AS winners
FROM (
SELECT SUBSTR(DATE_FORMAT(t.award_date,'%Y'),1,3) AS ccy
, t.category
, COUNT(1) AS count_winners
FROM mytable t
WHERE t.award = 'winner'
GROUP
BY SUBSTR(DATE_FORMAT(t.award_date,'%Y'),1,3)
, t.category
) s
The inline view aliased as s does the heavy lifting to get the result, the outer query does some formatting.
Note that this query does not return any "zero" counts.
If you also need to include "zero" counts, for all categories for all decades, that could be done as well, by introducing a row sources for "all category" and "all decades", and then doing a cross join between those and a left join to the inline view aliased as s.
The query above does not return include "0" count

Complex SQL Query (sum entries) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I am wondering if something like this could be implemented in SQL query.
Let say I have these tables:
Table Orders
id tax
01 800
02 255
Table DetailOrders
id price itemName
01 700 Book
01 500 Umbrella
01 100 Jacket
02 1000 Piano
Basically single entry of one table Orders corresponds to multiple entries in DetailOrders.
Is there are any way to write SQL query that would return something like this:
id tax sum-price all-names
01 800 1300 Book, Umbrella, Jacket
02 255 1000 Piano
It would sum the price of items with the same id, and somehow merge the names of the items with same id.
Could something like this be achieved?
How about something like
SELECT o.id,
o.tax,
sum(od.price) sum_price,
group_concat(itemName) all_names
FROM Orders o INNER JOIN
DetailOrders do ON o.id = do.id
GROUP BY o.id,
o.tax
Have a look at GROUP_CONCAT(expr)
This function returns a string result with the concatenated non-NULL
values from a group. It returns NULL if there are no non-NULL values.
It isn't hard:
select
o.id, o.tax,
sum(d.price),
group_concat(d.itemName)
from
orders as o
inner join detailOrders as d on o.id = d.id
group by
o.id