简体   繁体   中英

SQL: How do I combine columns into one, and filter out NULLs?

Here is my table. A list of ids with signup dates in columns newsletter, report, infographics.

在此处输入图片说明

I want to combine all those columns into one, without the NULLs

I've tried the following code

SELECT id, 
   combined_column
FROM (
    SELECT id, 
         CONCAT(newsletter, report, infographics) AS combined_column 
    FROM table
     )

WHERE combined_column is not NULL

But this just gives me a blank table. Is there a way to solve this? Thanks

Do you just want this?

select max(newsletter) as newsletter,
       max(report) as report,
       max(infographics) as infographics
from t;

Answer may depend on what database you're using, so caveat lector.

Is it the case that only one column will be non-null, as in your sample?

Then something like:

SELECT id, COALESCE(newsletter, infographics, report) FROM my_table;

might work for you...

If you are using Oracle, use NVL to replace NULL with empty string

SELECT id, 
   combined_column
FROM (
    SELECT id, 
         CONCAT(NVL(newsletter,''), NVL(report,''), NVL(infographics,'')) AS combined_column 
    FROM table
     )

WHERE combined_column is not NULL

I think you want coalesce which return the first not null value from the list (it you have more than one not null value in a row it'll still return the first one):

SELECT id, COALESCE(newsletter, report, infographics) AS combined_date
FROM t
WHERE COALESCE(newsletter, report, infographics) IS NOT NULL

SELECT ID,CONCAT(新闻稿,报告,信息图表)作为组合表的组合FROM表格WHERE新闻不为空且报告不为空且信息图表不为空

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM