Combining Columns QGIS Attribute Table
Many operators and functions in SQL (and therefore expressions) return NULL
if one of the parameters was NULL
The following examples demonstrate the behavior of various operators on a layer with the columns A
and B
.
"A" + "B"
NULL + 'text'
➝NULL
'a' + 'b'
➝'ab'
"A" || "B"
NULL || 'text'
➝NULL
'a' || 'b'
➝'ab'
CONCAT("A", "B")
CONCAT(NULL, 'text')
➝'text'
CONCAT('a', 'b')
➝'ab'
COALESCE("A", "B")
COALESCE(NULL, 'text')
➝'text'
COALESCE('a', 'b')
➝'a'
COALESCE('a', NULL)
➝'a'
COALESCE(NULL, NULL, 'Other')
➝'Other'
In your case you want to work with either CONCAT
or COALESCE
depending on the expected behaviour with multiple / no values.
You could use field calculator and follow these steps:
1- Create new field (string)
2- Use "Coalesce" Function
coalesce( "Value 1" , "Value 2" , 'value if No data')
Colaesce function returns the first not NULL
Select the layer in the layer panel and open the python console and run this snippet:
layer = iface.activeLayer()
layer.startEditing()
fields = layer.pendingFields()
fieldIndex = fields.indexFromName('newColumn')
for feature in layer.getFeatures():
if feature['value1']:
layer.changeAttributeValue(feature.id(),fieldIndex,feature['value1'])
if feature['value2']:
layer.changeAttributeValue(feature.id(),fieldIndex,feature['value2'])
if feature['value1'] and feature['value2']:
layer.changeAttributeValue(feature.id(),fieldIndex,feature['value2'] + ' ' + feature['value2']) # not sure what you want to do here if values found in both value1 and value2 fields
layer.commitChanges()