Can I subtract two attributes belonging to two different layers? In this case these would be two polygons holding DEPTH attribute (Depth1 - Depth2). Is this possible and if so how?
2 Answers
Another possibility is to use a virtual layer. Let's suppose you have two layers polygon_1
and polygon_2
with fields and values as follows:
Go to Menu Layer / Create layer / New Virtual Layer…
and paste this query:
SELECT p1.fid, depth_1-depth_2 as difference, p1.geometry
FROM polygon_1 as p1, polygon_2 as p2
where p1.fid = p2.fid
The features are connected with their common fid
. You not not state how the features should be connected, so I guess you have a common identifier in your data. However, you can adapt this to your needs. The attributes table of the new virtual layer looks like this, containing a newly calculated column for the difference depth_1 - depth_2
:
One possibility is to use QGIS expressions. If you are in the attribute table of a layer, open the field calculator and paste the following expression (adapting it to the names of your layers/fields) to get a value from an attribute field of another layer:
attribute (
get_feature_by_id (
'Polygon_2',
$id
),
'depth_2'
)
Let's suppose you have two layers:
- Polygon_1 with attribute
depth_1
(on this layer, you open the field calculator) - Polygon_2 with attribute
depth_2
(this is the value you want to get in the other layer)
You can get the value from one layer to the other one if they have a common field that they can be connected with - here: the same id
. Of course, it works also with other conditions. But since in your question you have not stated how the features of the two layers should be related, I suppose for demonstration purpose that they are connected by a commond id. If not, change the expression accordingly.
With the expression above, for each feature on Polygon_1
, you get the according value (of the feature with the same id) from Polygon_2
, namely value of field depth_2
. You can use this to copy values from Polygon_2
to Polygon_1
. If you add "depth_1"
- before the above expression, you get the difference depth_1
- depth_2
(what you want), see the screenshot:
join attributes by location
and then perform the substraction on the joined layer. Or you could create a virtual layer.