Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first row in each group using group by in sqlite

I have a table in sqlite. I am trying to get the first row of each group. Although there were earlier questions regarding the same. I couldn't find solution in sqlite.

My table looks like this:

select * from geoview
MaxOfStatecountpercent | statepoolnumber | STATECODE
123                       1234              CA
123                       1234              FL
234                       1678              TX
234                       1678              MN
234                       0987              FL
234                       0987              CA
234                       9876              TX

I would like to query the first of MaxOfStatecountpercent and first of STATECODE from each statepoolnumber. The equivalent access sql query is :

select first(MaxOfStatecountpercent), statepoolnumber, first(STATECODE) from geoview group by statepoolnumber;

And the output expected is :

First(MaxOfStatecountpercent) | statepoolnumber | First(STATECODE)
123                             1234              CA
234                             1678              TX
234                             0987              FL
234                             9876              TX

I tried with "limit 1 " but did not work. How can i get a query equivalent in sqlite?

like image 576
User1090 Avatar asked Feb 18 '16 18:02

User1090


People also ask

How do I SELECT the first row in 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 ).

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.

How do I get one row from multiple records in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.


1 Answers

The following works for me with your sample table data:

SELECT MaxOfStatecountpercent, statepoolnumber, STATECODE
FROM geoview
GROUP BY statepoolnumber
HAVING MIN(ROWID)
ORDER BY ROWID

This assumes that, based on your desired input, you want the 'first' state of each statepoolnumber group to be the first record (rather than 'first' by alphabetical order).

like image 98
Stidgeon Avatar answered Sep 22 '22 12:09

Stidgeon