您没有指定正在使用的 RDBMS,但您可以取消透视数据以返回包含非空值的数据。如果您没有UNPIVOT
功能,则可以使用UNION ALL
:
select col1, 'val1' col, val1
from yourtable
where val1 is not null
union all
select col1, 'val2' col, val2
from yourtable
where val2 is not null
union all
select col1, 'val3' col, val3
from yourtable
where val3 is not null
union all
select col1, 'val4' col, val4
from yourtable
where val4 is not null
union all
select col1, 'val5' col, val5
from yourtable
where val5 is not null
请参阅SQL Fiddle with Demo。
如果您有一个带有 unpivot 函数的 RDBMS,那么查询将类似于以下内容:
select col1, col, value
from yourtable
unpivot
(
value
for col in (val1, val2, val3, val4, val5)
) unpiv;
请参阅SQL Fiddle with Demo。数据作为行而不是单独的列返回,但结果是:
| COL1 | COL | VALUE |
-----------------------
| A | val1 | 1 |
| A | val5 | 1 |
| B | val2 | 1 |
| B | val4 | 1 |
| C | val1 | 1 |
| C | val3 | 1 |