如何使用SQL Server将列记录转换为行?

时间:2021-05-20 07:55:11

I have a table called RelationData which has 4 columns:

我有一个表,叫做关系数据,有4列:

RelationData

RelationData

Parent    child1    child2    child3
------------------------------------
111       112       113       117
111       222       223       224
444       441       442       443 

I want to show in one row if each one of any ID is matching.

如果任何ID都匹配,我想在一行中显示。

If user search 111 or 112 or 113 or 117 or 222 or 223 or 224, it has to show

如果用户搜索111或112或113或117或222或223或224,它必须显示

111
112
113 
117
222
223
224   

If user searches for 442, the result should be

如果用户搜索442,结果应该是。

444
441
442
443 

Even if I use case, it will show in column, not by row

即使我用大小写,它也会用列表示,而不是用行表示

1 个解决方案

#1


3  

You can unpivot the results. Here is one way:

你可以把结果挪开。这是一种方法:

select v.child
from relationdata rd outer apply
     (values (rd.child1), (rd.child2), (rd.child3), (rd.child4)) v(child)
where 111 in (rd.child1, rd.child2, rd.child3, rd.child4);

Note: have four columns with references like that is usually a sign of a poor database design. It would be better to have a relation table with a single child column and a "child number".

注意:拥有4列引用通常是数据库设计不佳的标志。最好有一个包含单个子列和“子数字”的关系表。

#1


3  

You can unpivot the results. Here is one way:

你可以把结果挪开。这是一种方法:

select v.child
from relationdata rd outer apply
     (values (rd.child1), (rd.child2), (rd.child3), (rd.child4)) v(child)
where 111 in (rd.child1, rd.child2, rd.child3, rd.child4);

Note: have four columns with references like that is usually a sign of a poor database design. It would be better to have a relation table with a single child column and a "child number".

注意:拥有4列引用通常是数据库设计不佳的标志。最好有一个包含单个子列和“子数字”的关系表。