简体   繁体   English

从多列中选择一个值

[英]Select values from multiple columns into single column

I have a table in a database that has 9 columns containing the same sort of data, these values are allowed to be null . 我在数据库中有一个表,该表有9列包含相同类型的数据,这些值允许为null I need to select each of the non-null values into a single column of values that don't care about the identity of the row from which they originated. 我需要将每个非空值都选择到单列的值中,这些值不关心它们源自的行的身份。

So, for a table that looks like this: 因此,对于一个看起来像这样的表:

+---------+------+--------+------+
|   Id    | I1   | I2     | I3   | 
+---------+------+--------+------+
|    1    | x1   | x2     |  x7  |
|    2    | x3   | null   |  x8  |
|    3    | null | null   |  null|
|    4    | x4   | x5     |  null|
|    5    | null | x6     |  x9  |
+---------+------+--------+------+

I wish to select each of the values prefixed with x into a single column. 我希望将每个以x开头的值选择到一列中。 My resultant data should look like the following table. 我得到的数据应如下表所示。 The order needs to be preserved, so the first column value from the first row should be at the top and the last column value from the last row at the bottom: 需要保留顺序,因此第一行的第一列值应该在顶部,而最后一行的最后列值应该在底部:

+-------+
| value |
+-------+
|  x1   |
|  x2   |
|  x7   |
|  x3   |
|  x8   |
|  x4   |
|  x5   |
|  x6   |
|  x9   |
+-------+

I am using SQL Server 2008 R2 . 我正在使用SQL Server 2008 R2 Is there a better technique for achieving this than selecting the value of each column in turn, from each row, and inserting the non-null values into the results? 是否有比从每行依次选择每一列的值并将非空值插入结果更好的技术呢?

You can use the UNPIVOT function to get the final result: 您可以使用UNPIVOT函数获得最终结果:

select value
from yourtable
unpivot
(
  value
  for col in (I1, I2, I3)
) un
order by id, col;

Since you are using SQL Server 2008+, then you can also use CROSS APPLY with the VALUES clause to unpivot the columns: 由于您使用的是SQL Server 2008+,因此还可以将CROSS APPLY与VALUES子句一起使用来取消透视列:

select value
from yourtable
cross apply
(
    values
        ('I1', I1),
        ('I2', I2),
        ('I3', I3)
) c(col, value)
where value is not null
order by id, col
SELECT value FROM (
   SELECT ID, 1 AS col, I1 AS [value] FROM t
   UNION ALL SELECT ID, 2,  I2 FROM t
   UNION ALL SELECT ID, 3,  I3 FROM t
) AS t WHERE value IS NOT NULL ORDER BY ID, col;

Try union like below : 尝试如下所示的并集:

    select value from
(
    select col1 as value from TestTable
    union
    select col2 as value from TestTable
    union
    select col3 as value from TestTable
) tt where value is not null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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