Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT query return 1 row from each group

This is a product table and have few million of records.

enter image description here

I want to list record as below:
Normally I use:

SELECT id, 
       product_name, 
       store_id 
FROM product
GROUP BY store_id 
ORDER BY id.


Currently having SQL performance issue. I need SQL query to output result like this.

enter image description here

like image 439
Vill Raj Avatar asked Jan 17 '13 08:01

Vill Raj


People also ask

How do I select the first row of a group in SQL?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ). You assign the row numbers within each group (i.e., year).

Can we use select * with GROUP BY?

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.

How do you select only the first rows for each unique value of a column in SQL?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on.


1 Answers

There are many alternatives to solves this, one which I recommend is to have joined a subquery which separately gets the latest ID (assuming that the column is AUTO_INCREMENTed) for each store_ID.

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  store_ID, MAX(ID) max_ID
            FROM    tableName
            GROUP BY store_ID
        ) b ON a.store_ID = b.store_ID AND
                a.ID = b.max_ID
  • SQLFiddle Demo

for better performance, be sure to have an index on these columns: ID and store_id.

UPDATE 1

if you want to have limit for every records, use this below,

SELECT ID, product_Name, store_ID
FROM   tableName a
WHERE
  (
     SELECT COUNT(*) 
     FROM   tableName b
     WHERE  b.store_ID = a.store_ID AND b.ID >= a.ID
  ) <= 2;
  • SQLFiddle Demo
like image 187
John Woo Avatar answered Sep 30 '22 22:09

John Woo