Select 2 columns in one and combine them

2020-05-24 19:38发布

问题:

Is it possible to select 2 columns in just one and combine them?

Example:

select something + somethingElse as onlyOneColumn from someTable

回答1:

Yes, just like you did:

select something + somethingElse as onlyOneColumn from someTable

If you queried the database, you would have gotten the right answer.

What happens is you ask for an expression. A very simple expression is just a column name, a more complicated expression can have formulas etc in it.



回答2:

(SELECT column1 as column FROM table )
UNION 
(SELECT column2 as column FROM table )


回答3:

Yes,

SELECT CONCAT(field1, field2) AS WHOLENAME FROM TABLE
WHERE ...

will result in data set like:

WHOLENAME
field1field2


回答4:

None of the other answers worked for me but this did:

SELECT CONCAT(Cust_First, ' ', Cust_Last) AS CustName FROM customer


回答5:

Yes it's possible, as long as the datatypes are compatible. If they aren't, use a CONVERT() or CAST()

SELECT firstname + ' ' + lastname AS name FROM customers


回答6:

The + operator should do the trick just fine. Keep something in mind though, if one of the columns is null or does not have any value, it will give you a NULL result. Instead, combine + with the function COALESCE and you'll be set.

Here is an example:

SELECT COALESCE(column1,'') + COALESCE(column2,'') FROM table1. 

For this example, if column1 is NULL, then the results of column2 will show up, instead of a simple NULL.

Hope this helps!



回答7:

Yes, you can combine columns easily enough such as concatenating character data:

select col1 | col 2 as bothcols from tbl ...

or adding (for example) numeric data:

select col1 + col2 as bothcols from tbl ...

In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.



回答8:

if one of the column is number i have experienced the oracle will think '+' as sum operator instead concatenation.

eg:

select (id + name) as one from table 1; (id is numeric) 

throws invalid number exception

in such case you can || operator which is concatenation.

select (id || name) as one from table 1;


回答9:

Your syntax should work, maybe add a space between the colums like

SELECT something + ' ' + somethingElse as onlyOneColumn FROM someTable



回答10:

I hope this answer helps:

SELECT (CAST(id AS NVARCHAR)+','+name) AS COMBINED_COLUMN FROM TABLENAME;


回答11:

select column1 || ' ' || column2 as whole_name FROM tablename;

Here || is the concat operator used for concatenating them to single column and ('') inside || used for space between two columns.