Select best selling products from each category

Asked

Viewed 235 times

0

Hello

I have a table with id, id_categoria, product name and quantity sold. I want to list the first products sold of each category, even if the second or third product of category "A" for example has sold more than the first of the category "B", I want to appear the first of each category!!!!

  • Add example of your starting table and expected result. Read this link https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-fazer-perguntas/5484#5484

1 answer

1

I want the first of each category to appear

Answering the above question....


Taking into account that your table is similar to the table described below:

+--------------+------------------+------+-----+---------+----------------+
| Field        | Type             | Null | Key | Default | Extra          |
+--------------+------------------+------+-----+---------+----------------+
| id           | int(11)          | NO   | PRI | NULL    | auto_increment |
| id_categoria | int(10) unsigned | NO   |     | NULL    |                |
| nome         | varchar(32)      | NO   |     | NULL    |                |
| qnt_vendida  | int(10) unsigned | YES  |     | 0       |                |
+--------------+------------------+------+-----+---------+----------------+

You can use the following query to list only the first product of each category

SET sql_mode='';
SELECT id_categoria, nome FROM produtos GROUP BY id_categoria;

Or else

SELECT id_categoria, ANY_VALUE(nome) FROM produtos GROUP BY id_categoria;

The GROUP BY will group all the identical values of the column "id_category", IE, it will return only the data without repeating them and with this we manage to capture the values.

SET sql_mode=''; and ANY_VALUE serve to avoid error ONLY_FULL_GROUP_BY. This error is generated when you use a non-aggregated value in a query who owns GROUP BY.

Demonstration

  • Excellent! Simple and effective.

  • @Joãohaskel If you have helped, don’t forget to mark as solved. Anything just ask.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.