MySQL Row more appear with multiple row same result - mysql

I have a query with a count with some group by, and I want to get the greater count. I can do with an order by and limit 1, but I have multiple results with the same count and then does not work for me.
How do I solve this problem?

With MySql 8+, you can use CTE to get the maximum count, and then retrieve all records with a count equal to the maximum count.
However, since CTE is not available in MySql 5.6, you'd need to use a sub-query to get the maximum count, and then write the main query which compares the count of each record to the maximum count retrieved in the subquery.
Here is a query I wrote. Maybe it's not the most efficient solution, but it gets the desired result.
SELECT
group_id, COUNT(record_id) c
FROM
table_name
GROUP BY group_id
HAVING c IN (
SELECT
MAX(sub_query.c)
FROM
(SELECT
group_id, COUNT(record_id) c
FROM
table_name
GROUP BY group_id) AS sub_query
)

If you are not going to do this using window functions, you can do:
SELECT group_id, COUNT(*) as cnt
FROM table_name
GROUP BY group_id
HAVING cnt = (SELECT COUNT(*)
FROM table_name
GROUP BY group_id
ORDER BY COUNT(*) DESC
LIMIT 1
) ;

Related

SQL order by count in an optimal way

When we have to print the count of a table while doing order by the count itself, is the below query optimal-
SELECT Group, COUNT( * )
FROM table
GROUP BY Group
ORDER BY COUNT( * ) DESC
I am thinking that the order by count(*) would do a count and then the select would also do the count. Does MySQL optimize this query so that count is done only once?
I was looking at SQL Order By Count when I thought if there was a better solution possible.

MySQL Subquery from ASC order to DESC order

select *, sum(sales_qty) as total_qty
from sales_details
left join sales on sales.salesid=sales_details.salesid
where month(sales.sales_date)='$m'
group by productid order by total_qty asc limit 2, 4
I have that sql that is sorted in ascending order. Now I want the results to be sorted in descending order. I have tried using subquery but doesn't work for me. Any help or suggestion is appreciated.
This is the sql that I have tried:
select * from (
select *, sum(sales_qty) as total_qty
from sales_details
left join sales on sales.salesid=sales_details.salesid
where month(sales.sales_date)='$m'
group by productid
order by total_qty asc
limit 2, 4
) as sub
order by sum(sales_qty) desc
Your query with the subquery should end
... ORDER BY sales_qty DESC
Why? When you say ... ORDER BY SUM(sales_qty) DESC you're converting the outer query into an aggregate query. Because that outer aggregate query has no GROUP BY clause, it necessarily has a one row result set.
The outer query treats the inner query as if it were a table, a virtual table. That virtual table has a column named sales_qty. It is the value by which you want to order.
Pro tip: Don't use SELECT * in aggregate queries. You're misusing the notorious nonstandard MySQL extension to GROUP BY, which means your result set contains unpredictable values. Read this. https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

MySQL 5.7 How to do GROUP BY with sorting?

Similar to this issue: MySQL 5.7 group by latest record
I'm not sure how to do this properly in 5.7. Also with possibility of 2nd sort column. Working query in 5.6 that I'm trying to replicate in 5.7:
SELECT id FROM test
GROUP BY category
ORDER BY sort1 DESC, sort2 DESC
id is not always the highest, so MAX(id) does not work.
Looking into the link above, the solution for single sort should be:
SELECT t1.*
FROM test t1
INNER JOIN (
SELECT category, max(sort) AS sort FROM test GROUP BY category
) t2 ON t2.category = t1.category AND t2.sort = t1.sort
But how will it work with 2 sorting?
You are using GROUP BY the wrong way.
Think of group by as a way to separate data row into different groups. Each group has multiple rows, based on the value of group by column.
Once you get those groups, selecting table columns (as in: select *) is like picking any row from that group randomly. This is not helpful nor useful.
Usually once we group records (or rows), we need to find meta information about those records. For example: get us the count of records in that group (as in: select count(*)), or the sum of values of a specific column in that group (as in: select sum(price)), or get the min, max or avg values.
So in a nutshell, when you use group by you should use on of the aggregation functions with it, otherwise it's not going to do you any good.
Why don't you have the ORDER BY at your outer query, instead?
SELECT *
FROM (
SELECT 100 AS id, 1 AS category, NULL AS sort
UNION
SELECT 200 AS id, 1 AS category, 2 AS sort
) dt
GROUP BY category
ORDER BY sort DESC;
It seems that what happened to the data when it was grouped, it took the first data while neglecting the ORDER BY DESC. On your first query, it ordered descending first then group by took the first record which is 200. And yes, this shouldn't be the way you should use GROUP BY. It is used in conjunction with aggregate functions.
when you select a column in a group by query that is not one of the columns you are grouping by, (ie, your id) you have no control over the value unless you use another aggregate function. If you want to sort, use MIN or MAX:
SELECT MAX(id), category, FROM `test2`
GROUP BY category; -- always returns 200
SELECT MIN(id), category, FROM `test2`
GROUP BY category; -- always returns 100

How to get the total records details along with the query which is having a limit

How to get the total records details along with the query which is having a limit
My MySQL query is given below
SELECT name FROM employees LIMIT 10
which will give me 10 rows, but the total records will be around 6000. How can we get that also along with the above query
Use a subquery:
SELECT name, (SELECT COUNT(*) FROM employees) AS cnt
FROM employees
LIMIT 10
Use a Sub-query
SELECT nameFROM,
(select count(1) from employees) as total_count
From employees
LIMIT 10
or CROSS JOIN
SELECT nameFROM,total_count
From employees
CROSS JOIN (select count(1) total_count from employees) A
LIMIT 10
Adding ORDER BY to your query will make the result consistent
You can use SQL_CALC_FOUND_ROWS option in your query which will tell MySQL to count total number of rows disregarding LIMIT clause. You still need to execute a second query in order to retrieve row count, but it’s a simple query and not as complex as your query which retrieved the data. Usage is pretty simple. In you main query you need to add SQL_CALC_FOUND_ROWS option just after SELECT and in second query you need to use FOUND_ROWS() function to get total number of rows
SELECT SQL_CALC_FOUND_ROWS name FROM employees WHERE LIMIT 10
SELECT FOUND_ROWS();
(SELECT NAME, 1 AS 'Obs' FROM employees LIMIT 10)
union select 'RecsinTable', count(*) from employees

GROUP BY in subquery to get accurate ranking

I'm trying to get the rank of a particular lap time of a specific track owned by a particular user.
There are multiple rows (laps) in this table for a specific user. So I'm trying to GROUP BY as seen in the subquery of FIND_IN_SET.
Right now MySQL (latest version) is complaining that my session_id,user_id,track_id,duration are not aggregated for the GROUP BY.
Which I don't understand why its complaining about this since the GROUP BY is in a subquery.
session_lap_times schema:
session_id, int
user_id, int
track_id, int
duration, decimal
This is what I've got so far.
SELECT
session_id
user_id,
track_id,
duration,
FIND_IN_SET( duration,
(SELECT GROUP_CONCAT( duration ORDER BY duration ASC ) FROM
(SELECT user_id,track_id,min(duration)
FROM session_lap_times GROUP BY user_id,track_id) AS aa WHERE track_id=s1.track_id)
) as ranking
FROM session_lap_times s1
WHERE user_id=1
It seems like its trying to enforce the group by rules on the parent queries as well.
For reference, this is the error I'm getting: http://imgur.com/a/ILufE
Any help is greatly appreciated.
If I'm not mistaken, the problem is here (broken out for clarity):
SELECT user_id,track_id,any_value(duration)
FROM session_lap_times
GROUP BY user_id
The query is probably barfing because track_id is in the select and not in the group by. That means the subselect doesn't stand on its own and makes the whole thing fail.
Try adding track_id to your group by and adjust from there.
You are grouping by user_id but you do not do any aggregation in select or having in the following sub-query
SELECT
user_id,any_value(track_id),any_value(duration)
FROM session_lap_times GROUP BY user_id
You are using GROUP_CONCAT in a wrong context in the following sub-query because you do not group any column in ranking temporary table.
(SELECT GROUP_CONCAT( duration ORDER BY duration ASC ) FROM
(SELECT user_id,track_id,any_value(duration)
FROM session_lap_times GROUP BY user_id,track_id) AS aa WHERE track_id=s1.track_id)
) as ranking