有一个退货样本:
id | value1 | value2
-------------------------
1 | AAAA | NULL
2 | NULL | BBBB
3 | CCCC | DDDD
需要得到它:
id | value
--------------
1 | AAAA
2 | BBBB
3 | CCCC
3 | DDDD
作为sql的一种方式我明白了吗?
答案 0 :(得分:4)
尝试这样的事情
select Id, value1 from yourtable
Where value1 is not null
Union all
select Id, value2 from yourtable
Where value2 is not null
答案 1 :(得分:1)
它应该与UNION
:
SELECT col1, col2 FROM table WHERE col2 IS NOT NULL
UNION
SELECT col3, col4 FROM table WHERE col4 IS NOT NULL
如果要保留重复项,请使用UNION ALL
答案 2 :(得分:1)
您可以尝试这样的事情
insert into #temp (id, value1, value2) values
(1,'AAAA', NULL)
,(2,NULL,'BBBB')
,(3, 'CCCC','DDDD')
select id, value1 as value from #temp where value1 is not null
union all
select id, value2 as value from #temp where value2 is not null
答案 3 :(得分:0)
这对于mysql IFNULL和sql-server ISNULL也很有帮助。
SELECT id, IFNULL(value1, value2) val1 FROM table1
UNION ALL
SELECT id, value2 FROM table1 WHERE value1 IS NOT NULL AND value2 IS NOT NULL