5

I have features and each of them has an attribute about what it is. In my case, I have points representing trees and each tree has its species name as an attribute.

enter image description here

I would like to group them by species name and using numbers from 1 to n as seen on picture and if possible, not by hand because sometimes I have hundreds of species. I was thinking of some kind of expression which includes $rownum and tried a few things but no results. SQL queries also came to mind, but I have limited experience with them and I've never given them a try in QGIS.

I really don't want to export data to a spreadsheet, I would like to solve this in QGIS if possible.

  • Does the number of the group matter? Or is it just the case that each uniqe tree name should get a uniqe number? – Matte Apr 16 '16 at 10:33
  • It doesn't matter, each unique species should be given a unique number. – Skye Apr 16 '16 at 12:35
3

There is an easy way that needs two steps from the db-manager and two tables that can be deleted in the end(there is a way with virtual tables, but i don´t get them to work properly from the db-manager).

  • go to db-manager and then to virtual layers and select your table with the trees; then start the sql-window

  • Enter into the query field: SELECT distinct(species) FROM "your table name"

run it, and save it as a new table (for example temp1) with the button down below

  • now open the same way the query again for your temp1-table and enter:

SELECT species,

rowid AS number from temp1

run it and save it as temp2

  • now you can join your table temp2 to your species-table by using the column species (via the joins function from your layer-preferences); Qgis does create a 1:n join and therefore the numbers are copied for each species

  • use the field calculator to add the numbers to your species table, then you can delete the temp1 and temp2

  • 1
    Unfortunately, an error message popped up just after I pasted the first operation: *** Query execution error on DROP TABLE IF EXISTS "groupby"; CREATE VIRTUAL TABLE "groupby" USING QgsVLayer(groupby20160416154358801);: 1 - near "group": syntax errorLÄLD?a0 *** I don't know what happened, should I set Virtual Layers to be usable somewhere? – Skye Apr 16 '16 at 14:56
  • What Qgis version you use? I did use 2.14. Otherwise iḿ not sure what could have lead to it. – Matte Apr 16 '16 at 15:23
  • My bad, first, I had to create a Spatialite database, and now it works perfectly, amazing! Huge thanks! – Skye Apr 16 '16 at 17:02
0

You could to use the "Field Calculator".

Try this expression for update your field "group":

CASE WHEN "species"='Ash' THEN 1 WHEN "species"='Beech' THEN 2 ...... ...... END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.