3

I have a sql statement i am running in postgres fine and would like to transfer it to a QgsExpression mainly because I have loaded the layer in Qgis.
My sql is:
select column a,column b from table1 GROUP BY column a,column b ORDER BY column b DESC limit 20. I do not know how to do so. Can I use python substitution when creating an expression.

expr = QgsExpression( "%s = 99" )% column a
3

As far as I know, the QgsExpression class allows you to select features from a layer that match a WHERE clause, i.e., the expression is a conditional that returns True or False (or unknown) for each feature. If the expression evaluates to True for a particular feature, that feature is selected in the map.

What I see from your PostGIS SQL expression is that you want a couple of columns from 20 ordered features. There is no WHERE clause. You could run this kind of expressions from the DBManager->SQL Window instead, which can give you subtables that you could eventually load into QGIS as new layers.

Now, answering your real question, you can use a Python variable to build your expression in this way:

colName= "myColumn"
expr = QgsExpression( "\"%s\" = 99" % colName ) 
print expr.expression() # this should print: "myColumn" = 99

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.