Get row position within a series of records in mysql - mysql

I have the following rows within a table.
MatchIDAuto CompetitionIDAuto TeamHome TeamAway MatchDate
4770 65 New Zealand South Africa 2017-02-19
4771 65 New Zealand South Africa 2017-02-21
4772 65 New Zealand South Africa 2017-02-25
4773 65 New Zealand South Africa 2017-03-01
4774 65 New Zealand South Africa 2017-03-04
What I need to be able to do is when I do the following:
select * from Match2 where MatchIDAuto=4772
Is know that it is the 3rd Match in the series. How could I dynamically calculate that with the query?

Without an ORDER BY clause there is no guarantee that row with id 4772 is the third row in the serie. That is because the database without an order by clause MAY generate different orders accordingly the Execution Plan.
So the first thing to do is to add an order by clause to your query. By the data it could be MatchIDAuto or MatchDate that I will leave by your choice. The query in MySql to get you the order number of a row will be:
select *
from (
select m.*,
#ord:=#ord+1 roworder
from Match2 m,
(select #ord:=0) t
ORDER BY MatchDate
) sub
where MatchIDAuto=4772;
This will return every column plus roworder with the order 3. On this query I choose the MatchDate field since, to me makes more sense on your data to be the column of your order by.
This technique will create a variable and sums it up to every row. You just wrap it in a subquery and query it.

Related

Fetch fixed set of duplicate records from table

I want to fetch records from a table that contains duplicate records. I want the output to be like only two duplicate records from each set of duplicate records in overall record output set.
example-
Name
Country
John
India
Mark
India
Chris
Russia
Feggy
England
Rain
Russia
Monesy
Russia
Bhumi
India
Peter
England
Bruice
England
Radhe
India
Output should have only two duplicate set of records from all duplicate of similar type as we can see in output below the country is repeating only two times and it took only first two counters of duplicate records in final record set -
Name
Country
John
India
Mark
India
Chris
Russia
Feggy
England
Rain
Russia
Peter
England
You can number the lines by the window and select only the first N.
Sorting should be chosen according to the business logic of the query.
For example:
;WITH numbered_name AS
(
SELECT *
, ROW_NUMBER() OVER (PARTITION BY t.Country ORDER BY t.Name) rn
FROM table t
)
SELECT Name
, Country
FROM numbered_name
WHERE rn <= 2

merge two columns, average with group by and find minimum with group by

The title probably doesn't accurately describe my question, sorry about that.
I have two tables:
2016Athletes:
Name Position 40_dash Year Overall
Jared Goff QB 4.82 2016 1
Carson Wentz QB 4.77 2016 2
Joey Bosa DE 4.88 2016 3
Ezekiel Elliott RB 4.47 2016 4
Jalen Ramsey CB 4.41 2016 5
............
and
2017Athletes:
Name Position 40_dash Year Overall
Myles Garrett DE 4.64 2017 1
Mitchell Trubisky QB 4.67 2017 2
Solomon Thomas DE 4.69 2017 3
Leonard Fournette RB 4.51 2017 4
Corey Davis WR NULL 2017 5
..............
I first want to merge the 40_dash columns and find the average, which I could do a couple ways, but the real problem I'm having is that after I find the average, I then want to group by position. I'm not sure it it's relevant, but the goal is to eventually select one particular athlete I know to be an impressive outlier and compare him to the average for all athletes, all defensive players, and then all linebackers and this grouping is my initial baseline for the following queries in my report.
My best crack at it would be
select avg(40_dash)
from ((select 40_dash from 2016Athletes) union ALL
(select 40_dash from 2017Athletes)
)sl GROUP BY Position;
However, I know that won't work because the group by function is not correct. I'm not sure how to called the 'unioned' column once I have them merged.
Afterwards, I want to find each athlete with the fasted 40_dash time, also grouped by position. A min() function would seem to do the job, but again the group by is what's tripping me up.
Thanks to anyone who can assist!
You need to select the position column in the subquery, so you can group by it in the main query.
SELECT Position, AVG(40_dash)
FROM (
SELECT Position, 40_dash FROM 2016Athletes
UNION ALL
SELECT Position, 40_dash FROM 2017Athletes
) as x
GROUP BY Position
See SQL select only rows with max value on a column for how to find the player with the fastest time in each group. You can then join that query with the above query, to compare the fastest to the average.

Trouble with Group By and Having in SQL

I am trying to learn Group By and Having but I can't seem to understand what happened here. I used w3shools SQL Tryit Editor.
The table I created is:
name age country
------------------------
Sara 17 America
David 21 America
Jared 27 America
Jane 54 Canada
Rob 32 Canada
Matthew 62 Canada
The Query I used:
select
sum(age), country
from
NewTable
group by
country
having
age>25;
I expected the query to categorize the information by country and use age>25 filter to create the results but here is the output:
sum(age) country
--------------------
65 America
148 Canada
What happened?! The result is sum of American and Canadian people in all ages.
The piece you're missing is specific to the having keyword. Using the having clause in your query is applied to the dataset after the grouping occurs.
It sounds like you are expecting the records with age less than 25 to be excluded from your query before grouping occurs. But, the way it works is the having clause excludes the total age for each group that sums to a total over 25.
If you want to exclude individual records before totaling the sum of the age, you could do something like this (using a where clause which is applied prior to grouping):
select sum(age), country from NewTable where age > 25 group by country;
A where clause puts a condition on which rows participate in the results.
A having clause is like a where, but puts a condition on which grouped (or aggregated) values participate in the results.
Either, try this:
select sum(age), country
from NewTable
where age > 25 -- where puts condition on raw rows
group by country
or this:
select sum(age), country
from NewTable
group by country
having sum(age) > 25 -- having puts a condition on groups
depending on what you're trying to do.

How to get results from Mysql database using WHERE if there is more than 1 criterion for identification?

id points year country
-----------------------------------
1 45 1998 Mexico
2 45 2000 Germany
3 47 2010 Russia
4 45 1970 China
5 49 2010 Austria
I wonder how can I take row results considering only 2 items from country column. For example only records where country is Germany and Mexico. When I try to get results where only 1 country is criterion the thing is easy:
SELECT * FROM List WHERE Country='Mexico';
the result is:
id points year country
-----------------------------------
1 45 1998 Mexico
but when I try to get results where 2 country items are criteria problems start. I tried:
SELECT * FROM List WHERE country='Mexico' AND Country='Germany';
SELECT * FROM List WHERE country='Mexico' AND 'Germany';
SELECT * FROM List WHERE country='Mexico','Germany';
SELECT * FROM List WHERE country='Mexico'AND WHERE country='Germany';
but no desired result:
id points year country
-----------------------------------
1 45 1998 Mexico
2 45 2000 Germany
I understand that maybe I committed logical error because there is no single record where country is Mexico and Germany at same time, and sql maybe understands claim exactly that way, but, how to write correctly in sql language: Give me results for records where countries are Mexico and Germany. Thanks.
You are looking for IN operator
SELECT * FROM List WHERE Country in ('Mexico','Germany');
Just use OR.
So instead of
SELECT * FROM List WHERE country='Mexico' AND Country='Germany';
it would be
SELECT * FROM List WHERE country='Mexico' OR country='Germany';
IN is also a good function to use, especially if you've got multiple values that you want to check against but that's been covered in the other answers.
You need to use or or in, you have been using and and asking mysql to find a row where country is both Mexico and Germany which is not true.
SELECT * FROM List WHERE Country in ('Mexico','Germany');
try this:
SELECT * FROM List WHERE country='Mexico' OR Country='Germany';
SQL is using logic. Natural language is not.
When you say that you want the results for a list of countries you need to specify so. This request corresponds to an logical or. Since the name can be one or the other, both are correct.
SELECT * FROM List WHERE Country = 'Mexico' OR Country = 'Germany'
To prevent further mistakes like these, I recommend that you look up logical operations in the docs (they are very good). MySQL or the PostGres, both should be fine.

MySQL: Selecting One Record When Others Have Same Data

I have a table of cities that all share the same area code:
367 01451 Harvard Worcester Massachusetts MA 978 Eastern
368 01452 Hubbardston Worcester Massachusetts MA 978 Eastern
369 01453 Leominster Worcester Massachusetts MA 978 Eastern
The table has multiple area codes, all with multiple cities.
What I'd like to do is only select one city from each area code and delete any extra cities from duplicate area codes. What would be the best query to accomplish this?
I believe:
Mysql4: SQL for selecting one or zero record
Is coming close to what I need but didn't quite get what/how those answers were working.
Note The "978" row is the "area_code" row, table name is "zip_code".
DELETE c.*
FROM zip_code c
JOIN (
SELECT area_code, MIN(id) AS mid
FROM zip_code
GROUP BY
area_code
) co
ON c.area_code = co.area_code
AND c.id <> co.mid