2

I have already viewed this link and still having issues - Creating Virtual Layer with PyQGIS.

When I create a virtual layer from the Layer -> Add/edit virtual layer and use this as a query it works as expected, i.e. column 1 contains the subtype, and column 2 is the sum of lengths of each subtype

select "Subtype", sum(Length)
from 'roads'
group by "Subtype"

However, when I use the console and paste this, I only get one row where column 1 is just called a "Subtype" and column 2 has the total length of all subtypes. How can I get the same results using Python console script as I do when manually creating a virtual layer using the menu?

from qgis.core import QgsVectorLayer, QgsProject
vlayer = QgsVectorLayer("?query=select 'Subtype', sum(Length) from 'roads' group by 'Subtype'", "vlayer", "virtual")
QgsProject.instance().addMapLayer(vlayer)
Taras
35.8k5 gold badges77 silver badges152 bronze badges
asked Oct 2, 2023 at 17:24

1 Answer 1

6

You need to remove the single quotes, or use double quotes for field name instead.

"?query=select Subtype, sum(Length) from 'roads' group by Subtype"

or

"?query=select \"Subtype\", sum(Length) from 'roads' group by \"Subtype\""
answered Oct 3, 2023 at 7:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.