I have an example table below:
+----+----+------+
|var1|var2|merged|
+----+----+------+
|a |b |a |
+----+----+------+
| |c |c |
+----+----+------+
| |x |x |
+----+----+------+
|c |d |c |
+----+----+------+
I want to merge var1
and var2
's values with the rule that whenever var1
has a value, it should be picked over var2
.
My code below does not achieve it and I am at a loss on how to implement this.
SELECT id, var1 & var2 AS merged
FROM myTable
All this code does is concatenated var1
and var2
's data which is not I want. The one I asked before is not working as desired anymore.
+----+----+------+
|var1|var2|merged|
+----+----+------+
|a |b |ab |
+----+----+------+
| |c |c |
+----+----+------+
| |x |x |
+----+----+------+
|c |d |cd |
+----+----+------+
The one below from this question does not take into account lone values :(
SELECT ID, var1, var2,
SWITCH (
var1 IS NOT NULL, var1,
var2 IS NOT NULL, var2,
) AS merged
FROM myTable;
+----+----+------+
|var1|var2|merged|
+----+----+------+
|a |b |a |
+----+----+------+
| |c | |
+----+----+------+
| |x | |
+----+----+------+
|c |d |c |
+----+----+------+
UPDATE
After using the methods provided in the answers, I have seen some of my records achieve what I presented in the first table above. But after looking through the other rows I managed to find ones that were skipped, as presented in the third table.
Below is the code I use and screenshots of the results.
SELECT ID, var1, var2,
# method 1
SWITCH (
var1 IS NOT NULL, var1,
var2 IS NOT NULL, var2
) AS switchResult,
# method 2
Nz(var1, var2) AS NzResult,
# method 3
Iif(var1 IS NULL, var2, var1) AS IifResult
FROM myTable;
The results here are what I wanted:
Note:
ID
,var1
,var2
,switchResult
,NzResult
,IifResult
are the column names for guide
But as I search for (Blanks)
there appears to be failed rows:
It seems that var1
's values if var2
's missing return correct queries but when var2
does have a value and var1
does not, some rows do not return correct queries.
Does anyone know why this happens? I already checked if var1
and var2
contains whitespace and they do not.