+ 2
How to show records in a Column which are existing in various columns in a table
A table has 3 columns A,B and C. I want to get these records in a Column D. Table structure A | B | C ------------ X | Null | Null -------------------- Null | Y | Null -------------------- Null | Null | Z And output should be D --- X Y Z
7 Antworten
+ 6
Thanks for letting us know. The proper etiquette is to select the answer that best fits by clicking the check mark next to the accepted answer.
+ 4
I tested this in MySQL:
select a, b, c, concat(COALESCE(a, ''), COALESCE(b, ''), COALESCE(c, '')) from t;
+------+------+------+-----------------------------------------------------------+
| a | b | c | concat(COALESCE(a, ''), COALESCE(b, ''), COALESCE(c, '')) |
+------+------+------+-----------------------------------------------------------+
| x | NULL | NULL | x |
| NULL | y | NULL | y |
| NULL | NULL | z | z |
+------+------+------+-----------------------------------------------------------+
3 rows in set (0.01 sec)
The COALESCE function helps convert null to empty string there.
concat will return null if any of its parameters are null. COALESCE makes sure none of the actual parameters to concat are null.
COALESCE is supported in both MySQL and Microsoft SQL Server but I didn't check other vendors.
+ 4
Josh Greig You can actually simplify your approach as follows:
SELECT COALESCE(a, b, c, "z") as D
FROM coalesce_demo;
This query will use the first non null value available.
To take this demo further, I specify a default value to be "z" when all other columns are NULL.
Check out the SQL Fiddle I created to demonstrate this:
http://sqlfiddle.com/#!9/6554a0/2/0
This returns a single column result set:
D
---
a
b
z
c
...
...
...
+ 4
Durgesh Verma Were you able to get your query to work?
+ 1
How do you want to combine those values into one column? Are they strings that can be concatenated together?
If yes, you could do something like this:
select a, b, c, concat(a, b, c) from mytable
0
Josh Greig I have updated my question. Please take a look and help me out of this😊
0
Yes Thanks