I have column 1 and column 2, and want to combine them into column 3 of the same table. If the column 2 is null then display column 1 value, if column 1 is null, them display column 2 data. If both of them are null, then display null. I tried two things:
1) using CONCAT
SELECT CONCAT(Column1, Column2) AS Column3 FROM TEST_ATTRIBUTES
.
It just merges the columns only when both of them are not null. otherwise it just prins null.
2) using (column1 + column 2).
SELECT (Column1 + Column2) AS Column3 FROM TEST_ATTRIBUTES
.
doesn't show desired output.
I'm writing this code in java. Thanks
You can combine two or more table cells located in the same row or column into a single cell. For example, you can merge several cells horizontally to create a table heading that spans several columns. Select the cells that you want to merge. Under Table Tools, on the Layout tab, in the Merge group, click Merge Cells.
To unmerge cells immediately after merging them, press Ctrl + Z. Otherwise do this: Click the merged cell and click Home > Merge & Center. The data in the merged cell moves to the left cell when the cells split.
use COALESCE()
, this doesn't concatenate but returns the first non-null value from the list.
SELECT Column1,
Column2,
COALESCE(Column1, Column2) AS Column3
FROM TEST_ATTRIBUTES
if there are chances that both of them are null,
SELECT Column1,
Column2,
IF(Column1 IS NULL AND Column2 IS NULL, NULL, CONCAT(COALESCE(Column1,''), COALESCE(Column2,''))) AS Column3
FROM TEST_ATTRIBUTES
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With