Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 尝试将包含多个列的SQL Server表排序为只有两列的表_Sql Server - Fatal编程技术网

Sql server 尝试将包含多个列的SQL Server表排序为只有两列的表

Sql server 尝试将包含多个列的SQL Server表排序为只有两列的表,sql-server,Sql Server,我有一个SQL Server表,需要帮助排序。我的当前表的第一列包含名为Parent的信息,后面的列是child1、child2、child3、 范例 Parent Child1 Child2 Child3 ....... 001 003 004 002 005 006 009 我需要对表进行排序,这样我的结果将有两列。第一列将包含父列,第二列将是子列,它将包含与其父列关联的每个子列

我有一个SQL Server表,需要帮助排序。我的当前表的第一列包含名为Parent的信息,后面的列是child1、child2、child3、

范例

Parent    Child1     Child2     Child3   .......  
001          003        004  
002          005        006        009
我需要对表进行排序,这样我的结果将有两列。第一列将包含父列,第二列将是子列,它将包含与其父列关联的每个子列

范例

Parent     Children  
001            003  
001            004  
002            005  
002            006  
002            009 
等等


我对SQL相当陌生,不知道如何处理这个问题。有什么想法吗?

标准查询不能在一行中生成多行,但您可以将丑陋的东西拼凑在一起,例如:

SELECT Parent, Child1
FROM yourtable

UNION ALL

SELECT Parent, Child2
FROM yourtable

UNION ALL 

etc...

在这里,为每个要组合的“子”列重复union/select

尝试
UNPIVOT

select 
    parent, child,
    val
from (
    select 001 as parent, 003 as child1, 004  as child2, 007 as child3 union all 
    select 002, 005, 006, 009
) x
unpivot (
    val for child in (child1, child2, child3)
) y

唯一的问题是,您必须显式地列出每一列,因此如果子列数不同,则必须使用动态sql。

An
UNPIVOT
可以做到这一点

SELECT Parent, Child FROM table
UNPIVOT (Child FOR ChildNo IN (Child1, Child2, Child3)) u


显然,在实际的查询中,您会将
Child4
添加到
Child21
到逗号分隔的列表中。

一个
UNPIVOT
不完全符合OP的要求吗?这不会令人惊讶。我对tsql处理得不够周到,我只是把它当作一个问题,因为我自己也不确定。检查交叉应用或取消PIVOT功能,并尝试自己找到一个解决方案。