How can I narrow down this query by using the max function? - mysql

I am using PHP MyAdmin. I want the result of this query to be Willard Wildcats and 7, but I can't figure out how to do it by using the max function rather than the order by and limit functions. I need to use the max function
Select Team_Name, Count(*)
From Number_3
Group By Team_Name
The result of this query should be
Willard Wildcats and 7

Use LIMIT clause :
SELECT Team_Name, Count(*) AS CNT
FROM Number_3
GROUP BY Team_Name
ORDER BY CNT DESC
LIMIT 1;
If you are limited with LIMIT clause then use subquery :
SELECT Team_Name, Count(*) AS CNT
FROM Number_3
GROUP BY Team_Name
HAVING Count(*) = (SELECT MAX(CNT)
FROM (SELECT Team_Name, Count(*) AS CNT
FROM Number_3
GROUP BY Team_Name
) t
);
If you are working latest version of MySQL then it will be more easier with ranking function :
SELECT t.*
FROM (SELECT Team_Name, Count(*) AS CNT,
DENSE_RANK() OVER (ORDER BY Count(*) DESC) AS Seq
FROM Number_3
GROUP BY Team_Name
) t
WHERE Seq = 1;

You need to write where condition and select a column using max function
Select Team_Name, Count(*) From Number_3 where Team_Name=(select max(Count(*)) from Number_3)

Related

get the most common value for each column

I'm attempting to create an SQL query that retrieves the total_cost for every row in a table. Alongside that, I also need to collect the most dominant value for both columnA and columnB, with their respective values.
For example, with the following table contents:
cost
columnA
columnB
target
250
Foo
Bar
XYZ
200
Foo
Bar
XYZ
150
Bar
Bar
ABC
250
Foo
Bar
ABC
The result would need to be:
total_cost
columnA_dominant
columnB_dominant
columnA_value
columnB_value
850
Foo
Bar
250
400
Now I can get as far as calculating the total cost - that's no issue. I can also get the most dominant value for columnA using this answer. But after this, I'm not sure how to also get the dominant value for columnB and the values too.
This is my current SQL:
SELECT
SUM(`cost`) AS `total_cost`,
COUNT(`columnA`) AS `columnA_dominant`
FROM `table`
GROUP BY `columnA_dominant`
ORDER BY `columnA_dominant` DESC
WHERE `target` = "ABC"
UPDATE: Thanks to #Barmar for the idea of using a subquery, I managed to get the dominant values for columnA and columnB:
SELECT
-- Retrieve total cost.
SUM(`cost`) AS `total_cost`,
-- Get dominant values.
(
SELECT `columnA`
FROM `table`
GROUP BY `columnA`
ORDER BY COUNT(*) DESC
LIMIT 1
) AS `columnA_dominant`,
(
SELECT `columnB`
FROM `table`
GROUP BY `columnB`
ORDER BY COUNT(*) DESC
LIMIT 1
) AS `columnB_dominant`
FROM `table`
WHERE `target` = "XYZ"
However, I'm still having issues figuring out how to calculate the respective values.
You might get close, if we want to get percentage values we can try to add COUNT(*) at subquery to get max count by columnA and columnB then do division by total count
SELECT
SUM(cost),
(
SELECT tt.columnA
FROM T tt
GROUP BY tt.columnA
ORDER BY COUNT(*) DESC
LIMIT 1
) AS columnA_dominant,
(
SELECT tt.columnB
FROM T tt
GROUP BY tt.columnB
ORDER BY COUNT(*) DESC
LIMIT 1
) AS columnB_dominant,
(
SELECT COUNT(*)
FROM T tt
GROUP BY tt.columnA
ORDER BY COUNT(*) DESC
LIMIT 1
) / COUNT(*) AS columnA_percentage,
(
SELECT COUNT(*)
FROM T tt
GROUP BY tt.columnB
ORDER BY COUNT(*) DESC
LIMIT 1
) / COUNT(*) AS columnB_percentage
FROM T t1
If your MySQL version supports the window function, there is another way which reduce table scan might get better performance than a correlated subquery
SELECT SUM(cost) OVER(),
FIRST_VALUE(columnA) OVER (ORDER BY counter1 DESC) columnA_dominant,
FIRST_VALUE(columnB) OVER (ORDER BY counter2 DESC) columnB_dominant,
FIRST_VALUE(counter1) OVER (ORDER BY counter1 DESC) / COUNT(*) OVER() columnA_percentage,
FIRST_VALUE(counter2) OVER (ORDER BY counter2 DESC) / COUNT(*) OVER() columnB_percentage
FROM (
SELECT *,
COUNT(*) OVER (PARTITION BY columnA) counter1,
COUNT(*) OVER (PARTITION BY columnB) counter2
FROM T
) t1
LIMIT 1
sqlfiddle
try this query
select sum(cost) as total_cost,p.columnA,q.columnB,p.columnA_percentage,q.columnB_percentage
from get_common,(
select top 1 columnA,columnA_percentage
from(
select columnA,count(columnA) as count_columnA,cast(count(columnA) as float)/(select count(columnA) from get_common) as columnA_percentage
from get_common
group by columnA)s
order by count_columnA desc
)p,
(select top 1 columnB,columnB_percentage
from (
select columnB,count(columnB) as count_columnB, cast(count(columnB) as float)/(select count(columnB) from get_common) as columnB_percentage
from get_common
group by columnB) t
order by count_columnB desc)q
group by p.columnA,q.columnB,p.columnA_percentage,q.columnB_percentage
so if you want to get the percent and dominant value you must make their own query like this
select top 1 columnA,columnA_percentage
from(
select columnA,count(columnA) as count_columnA,cast(count(columnA) as float)/(select count(columnA) from get_common) as columnA_percentage
from get_common
group by columnA)s
order by count_columnA desc
then you can join with the sum query to get all value you want
hope this can help you

Get maximum value from two values

I have a table which gives the no of rides by a rider at each stand point. I need to find the stand for each rider for which he has the maximum rides.
My first result is in this format: 1
I require my final result like this: 2
I'm currently using this query, but I know it can be done in a better manner. Any suggestions would be helpful.
select c.rider_id, c.end_stand, b.max_rides
from
(select rider_id, max(rides) as max_rides
from
(select rider_id, end_stand, count(id) as rides
from ride where end_stand is not null
group by 1,2) a
group by 1
order by 2 desc, 1) b
join
(select rider_id, end_stand, count(id) as rides
from ride where end_stand is not null
group by 1,2) c
on c.rider_id = b.rider_id and c.rides = b.max_rides
order by 3 desc, 2,1
Before window functions, one method is a correlated subquery in the having clause:
select rider_id, end_stand, count(*) as rides
from ride r
where end_stand is not null
group by rider_id, end_stand
having count(*) = (select count(*)
from ride r2
where r2.end_stand is not null and
r2.rider_id = r.rider_id
group by r2.rider_id, r2.end_stand
order by count(*) desc
limit 1
);
With window functions, this is, of course, much simpler:
select *
from (select rider_id, end_stand, count(*) as rides
rank() over (partition by rider_id order by count(*) desc) as seqnum
from ride r
where end_stand is not null
group by rider_id, end_stand
) r
where seqnum = 1;
Both these will return duplicates, if there are ties for the max. The second version is easy to fix, if you want only one row: use row_number() instead of rank().

overall rank working with using FIND_IN_SET but department wise not working rank query

I have tried to get overall rank using FIND_IN_SET, it's working, at the same time using department_id 105 it's working.
query:SELECT id, emp_id ,emp_name, dept_id, total_pt, FIND_IN_SET( total_pt, ( SELECT GROUP_CONCAT( total_pt ORDER BY total_pt DESC )
FROM performance_score ) ) AS rank,overall_rank FROM performance_score_bk where dept_id = 105
But after i tried to get the rank with department_id 111, it'not starting with rank 1, it's starting 8 and no proper order.
Please check the inform me where i did a mistake.
query:SELECT id, emp_id ,emp_name, dept_id, total_pt, FIND_IN_SET( total_pt, ( SELECT GROUP_CONCAT( total_pt ORDER BY total_pt DESC )
FROM performance_score ) ) AS rank,overall_rank FROM performance_score_bk where dept_id = 111
Simulating rank on MySQL versions 5.7 and earlier is a real pain-in-the-neck. If you have a long term need for rank, or other analytic functions, then consider upgrading to MySQL 8+. In MySQL 8 we can easily write:
SELECT
dept_id,
total_pt,
RANK() OVER (PARTITION BY dept_id ORDER BY total_pt DESC) `rank`,
RANK() OVER (ORDER BY total_pnt DESC) overall_rank
FROM yourTable
ORDER BY
dept_id,
total_pt DESC;

How to get the maximum count, and ID from the table SQL

**castID**
nm0000116
nm0000116
nm0000116
nm0000116
nm0000116
nm0634240
nm0634240
nm0798899
This is my table (created as a view). Now I want to list the castID which has the most count (in this case which is nm0000116, and how many occurences/count it has in this table ( should be 5 times) and I'm not quite sure which query to use
try
Select CastId, count(*) countOfCastId
From table
Group By CastId
Having count(*)
= (Select Max(cnt)
From (Select count(*) cnt
From table
Group By CastId) z)
SELECT
MAX(E),
castId
FROM
(SELECT COUNT(castId) AS E,castId FROM [directors winning movies list] GROUP BY castId) AS t
You could just return the topmost count using LIMIT:
SELECT castID,
COUNT(*) AS Cnt
FROM atable
GROUP BY castID
ORDER BY Cnt DESC
LIMIT 1
;
However, if there can be ties, the above query would return only one row. If you want all the "winners", you could take the count from the above query as a scalar result and compare it against all the counts to return only those that match:
SELECT castID,
COUNT(*) AS Cnt
FROM atable
GROUP BY castID
HAVING COUNT(*) = (
SELECT COUNT(*)
FROM atable
GROUP BY castID
ORDER BY Cnt DESC
LIMIT 1
)
;
(Basically, same as Charles Bretana's approach, it just derives the top count differently.)
Alternatively, you could use a variable to rank all the counts and then return only those that have the ranking of 1:
SELECT castID,
Cnt
FROM (
SELECT castID,
COUNT(*) AS Cnt,
#r := IFNULL(#r, 0) + 1 AS r
FROM atable
GROUP BY castID
ORDER BY Cnt DESC
) AS s
WHERE r = 1
;
Please note that with the above method the variable must either not exist or be pre-initialised with a 0 or NULL prior to running the query. To be on the safe side, you could initialise the variable directly in your query:
SELECT s.castID,
s.Cnt
FROM (SELECT #r := 0) AS x
CROSS JOIN
(
SELECT castID,
COUNT(*) AS Cnt,
#r := #r + 1 AS r
FROM atable
GROUP BY castID
ORDER BY Cnt DESC
) AS s
WHERE s.r = 1
;

SQL query max(), count()

the database schema looks like
employee(employee_name,street,city)
works(employee_name,company_name,salary)
company(company_name,city)
manages(employee_name,manager_name)
the query needed to do is:
find the company that has the most employees.
I could find out the maximum count by the query:
SELECT max( cnt ) max_cnt
FROM (
SELECT count( employee_name ) cnt, company_name
FROM works
GROUP BY company_name
)w1;
But now I can't find out the name of the company. If anyone has some idea please share.
To get the entire row containing the maximum value you can use ORDER BY ... DESC LIMIT 1 instead of MAX:
SELECT company_name, cnt
FROM (
SELECT company_name, count(employee_name) AS cnt
FROM works
GROUP BY company_name
) w1
ORDER BY cnt DESC
LIMIT 1
How about something like:
SELECT count( employee_name ) cnt, company_name
FROM works
GROUP BY company_name
ORDER BY cnt DESC
LIMIT 1;
Edit:
Corrected above for MySQL
SELECT company_name,count(*) as cnt
FROM works
GROUP BY company_name
ORDER BY cnt DESC
select company_name
from works
group by company_name
having count(distinct employee_name)>=all(select count(distinct employee_name)
from works
group by company_name )
Here's the working query
Select * from(SELECT count(EmpName)cnt, CName FROM works GROUP BY CName Order By cnt desc) where ROWNUM = 1;
This looks like a course question.
If more than one companies have the same largest number of employees the query with LIMIT doesn't work. "ORDER BY" didn't filter out useless info. Thus we have the following solution
SELECT company_name FROM
(SELECT company_name, count(employee_name) cnt
FROM works
GROUP BY company_name)
JOIN
(SELECT max(cnt) max_cnt
FROM (
SELECT count(employee_name) cnt
FROM works
GROUP BY company_name
)) ON cnt = max_cnt
select company_name from works_for
group by company_name
having count(employee_name) = (select max(count(employee_name))from works_for
group by company_name);
In Oracle
select company_name, count(*) as count
from works
group by company_name
having count(*) >= all(select count(*) from works group by company_name)