Choose company with most records mysql - mysql

I have a mysql database with records from different companies. I need to select records from companies which have the most, second most and third most records and plot their number of records per year. How do I select them?
Many thanks.
EDIT:
The table would look something like this:
Company Year
A 1999
A 1999
B 1999
C 1999
A 2000
C 2000
A 2003
So if I select the company with the most records, A has the most records, and the output is;
Year Total
1999 2
2000 1
2003 1
And for the company with second most records, the output is ( in this case, company C)
Year Total
1999 1
2000 1
Third most will be company B.

I'd say something like
SELECT company,COUNT(company) AS rec,year
FROM your_table GROUP BY company, year ORDER BY rec DESC LIMIT 3;

most_frequent:
SELECT year, COUNT(year) AS total FROM your_table
WHERE company =
(SELECT company, COUNT(company) AS c
FROM your_table
GROUP BY c
ORDER BY c DESC
LIMIT 0,1)
second most:
SELECT year, COUNT(year) AS total FROM your_table
WHERE company =
(SELECT company, COUNT(company) AS c
FROM your_table
GROUP BY c
ORDER BY c DESC
LIMIT 1,1)
third most:
SELECT year, COUNT(year) AS total FROM your_table
WHERE company =
(SELECT company, COUNT(company) AS c
FROM your_table
GROUP BY c
ORDER BY c DESC
LIMIT 2,1)
In order to get two dimensional output in one query:
SELECT company, year, COUNT(year) AS total FROM your_table
INNER JOIN
(SELECT company, COUNT(company) AS c
FROM your_table
GROUP BY c
ORDER BY c DESC) AS t1
ON your_table.company = t1.company
ORDER BY t1.c DESC
I'm sorry, I haven't tested it. Just leave a comment if you have any trouble.

Related

Get distinct values from groups in MySQL

I want to get the id of the lowest points from each team (the team field).
My query works but i need to make sure the following query is good enough with a large table.
I need Simplification and Optimization.
Query:
SELECT T.id from teams as T
INNER JOIN (
SELECT MIN(T1.points) AS P FROM teams AS T1
GROUP BY T1.team LIMIT 5
) TJOIN ON T.points IN (TJOIN.P)
GROUP BY T.team
ORDER BY T.points ASC LIMIT 5
Table teams
id
team (foreign_key)
points (indexed)
1
a
100
2
a
101
3
b
106
4
c
105
5
c
102
Result
id
1
5
3
I believe the query you are looking for is:
SELECT MIN(T.id)
FROM teams as T
INNER JOIN (
SELECT team, MIN(points) AS min_points
FROM teams
GROUP BY team LIMIT 5
) TJOIN
ON T.team = TJOIN.team
AND T.points = TJOIN.min_points
GROUP BY T.team
ORDER BY T.points ASC
LIMIT 5
You need to join based on both the column being grouped by and the min value. Consider the result of your query if multiple teams had a score of 100.
Another way of doing this is to use ROW_NUMBER():
SELECT id
FROM (
SELECT id, points, ROW_NUMBER() OVER (PARTITION BY team ORDER BY points ASC, id ASC) rn
FROM teams
) t
WHERE rn = 1
ORDER BY points ASC
LIMIT 5

Mysql Select Sum but last three records

I have table with fields Customer date and amount
I want to sum Amount grouped by customer except the last two amounts of every customer by date
sample data
customer date amount
a 2020-10-1 100
a 2020-10-2 150
a 2020-10-3 30
a 2020-10-4 20
b 2020-10-1 1
b 2020-10-5 13
b 2020-10-7 50
b 2020-10-9 18
desired result
Customer Amount
A 150
B 14
something like
select Customer ,
SUM(amount- last 2 amount)
From TableA
Group By Customer
One option uses window functions, available in MySQL 8.0:
select customer, sum(amount) total_amount
from (
select a.*, row_number() over(partition by customer order by date desc) rn
from tablea a
) a
where rn > 2
group by customer
In earlier versions, an alternative uses a correlated subquery that returns the third latest date per customer for filtering:
select customer, sum(amount) total_amount
from tablea a
where date <= (select a1.date from tablea a1 where a1.customer = a.customer order by a1.date desc limit 2, 1)
group by customer

MySQL Count and SUM from second table with group by

I'm trying to get sales and quantity sale by crossing two tables, group by the first one and sum from the second one.
First table has sales/operations: id_sales, sales_rep
Second table has sales details: id_sales_details, id_sales, quantity
What I need to know is how many operations had each sales_rep and what was the total quantity sum of all those sales.
This MySQL query gives me the first part:
SELECT sales.sales_rep, count(*) AS sales
from sales
Group by sales_rep
Order by sales DESC
What I cannot solve is how to add to that query the second part I need. The result should look something like:
sales_rep sales quantity
Claire 4 13
Peter 2 18
Mary 1 8
John 1 7
Here's a Fiddle to make things clearer: http://sqlfiddle.com/#!9/708234/5
SELECT s.sales_rep, count(*) AS operations, sum(d.quantity)
from sales s, sales_details d
where s.id_sales = d.id_sales
Group by s.sales_rep
Order by operations DESC;
Quick solution
SELECT w.sales_rep, w.sales, SUM(quantity) as quantity
FROM
(SELECT s.sales_rep, t.sales,d.quantity FROM sales AS s
INNER JOIN sales_details AS d ON s.id_sales = d.id_sales
INNER JOIN
(SELECT sales_rep, count(*) AS sales
from sales
Group by sales_rep
Order by sales DESC ) AS t
ON s.sales_rep = t.sales_rep) AS w
GROUP BY w.sales_rep, w.sales
ORDER BY w.sales_rep ASC

MYSQL: How to get Maximum and Second Maximum Date in single query

I am trying to select Maximum Date and Second Max Date but can't get success.
This is table data.
ID Country DATE
1 Canada 2016-05-26
2 Canada 2016-05-25
3 Canada 2016-05-24
4 USA 2016-04-02
5 USA 2016-04-01
6 USA 2016-03-20
Expecting Output
Country Max_Date 2nd_Date
Canada 2016-05-26 2016-05-25
USA 2016-04-02 2016-04-01
What I have done so for:
Get Max Date using this query.
select Country, MAX(Date) from tbl GROUP BY (Country);
For Second Max date but failed to get result:
SELECT Country, MAX(date) FROM tbl WHERE Date NOT IN
( select MAX(FROM) from tbl GROUP BY (Country)) GROUP BY (Country)
What should I try to get expected output. Thanks
Or you could try this
SELECT s.Country, Max(s.Date) Max_Date,
(SELECT t.Date
FROM tbl t
Where s.Country=t.Country
ORDER BY Date DESC
LIMIT 1,1) 2nd_Date
FROM tbl s
GROUP BY COUNTRY;
The LIMIT clause is zero based, so using parameters 1,1 skips the first (ie max) value & returns just one value (2nd max).
NOTE - if the max date is duplicated the query will return Max_Date & 2nd_Date as the same value - if that is not what you want, then you can add DISTINCT to the inner query.
No need for nested queries to solve this:
SELECT t1.country, max(t1.date), max(t2.date)
FROM tbl t1
JOIN tbl t2 ON t1.country = t2.country AND t2.date < t1.date
GROUP BY t1.country;
This can be a pain. Here is one method:
select t.country, maxdate, max(t.date) as secondate
from tbl t left join
(select country, max(date) as maxdate
from tbl
group by country
) c
on t.country = c.country and t.date < c.maxdate
group by t.country;
Try this one
Select Country, MAX(Date) As Date From tbl GROUP BY Country Order By Date Desc Limit 2;

My sql Group By case for getting highest paid employee in specific year

there is two table
1 Employee
2 salary
Employee : eId, ename, salaryId
Salary : salaryId, eId, salary, date
salary table contains monthly record of employee salary,
like:
eId date salary
1 2015-jan-01 10000
1 2015-feb-01 10000
1 2015-mar-01 10000
1 2014-jan-01 10000
1 2014-feb-01 10000
1 2014-mar-01 10000
2 2015-jan-01 10000
2 2015-feb-01 10000
2 2015-mar-01 10000
2 2014-jan-01 10000
2 2014-feb-01 10000
2 2014-mar-01 20000
so the query is to give me highest paid employee in specific year for ex: 2014
so here using group by with date and sum of salary output is :
empid - empname - sum(salary)
2 - xyz - 40000
Try it with something like this ... i just took a glance to point you toward right direction, this query might need some fixing
Select TOP 1 emp.eid, emp.ename, sal.salary
from Employee emp
join Salary sal on emp.salaryID = sal.salaryID
where DATEPART(yy,sal.date) = 2014
order by sal.salary desc
Good luck
Something like this could work
with salaries as (
select to_char(date,'yyyy') y, eld, sum(salary) s_sal
from salary
group by to_char(date,'yyyy'), eld)
select eld
from salaries s
where s_sal = (select max(s_sal) from salaries where y=s.y)
and s.y='2014';
But you didn't specify DB, so there is Oracle syntax.
And I didn't join with Employee table, but believe it isn't hard to add it.
If the requirement is to get the list of highest paid employee in each year then this can be achieved by a "Ranking" logic.
Something like this:
SELECT
Year(SalaryMonthDate) AS [Payroll Year],
EID,
Sum(Amout) AS [Annual Salary],
RANK() OVER(PARTITION BY Year(SalaryMonthDate) ORDER BY Sum(Amout) DESC) [Rank]
FROM tblSalary
GROUP BY Year(SalaryMonthDate), EID
Hope this helps.
MySQL Code,
SELECT Top 1 E.ename EmployeeName,
MAX(salary) AS EmployeeSalary
FROM Employee E
INNER JOIN Salary S
ON E.salaryID = S.salaryID
WHERE YEAR(S.Date) = 2014
GROUP BY
E.eId,
E.ename
#highest paid emp in specific year
SELECT e.empId,e.empName,SUM(s.salary),s.salDate
FROM emp e INNER JOIN salary s ON e.empId = s.empId
WHERE YEAR(s.salDate)=2009 GROUP BY s.empId ORDER BY SUM(s.salary) DESC LIMIT 1;