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?
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 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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With