Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.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 将主行添加到查询结果_Sql_Sql Server 2005 - Fatal编程技术网

Sql 将主行添加到查询结果

Sql 将主行添加到查询结果,sql,sql-server-2005,Sql,Sql Server 2005,如何在MSSQL 2005中将主行添加到查询结果中。这是一个我需要返回的示例 下面是两个问题 问题1 select product_id, sku from products 问题2 select product_id, sku from childproducts 结果应该是这样的。(当然没有查询1) 您可以使用UNION ALL组合它们,例如 select 1 as Sorter, product_id, sku from products UNION ALL select 2, pro

如何在MSSQL 2005中将主行添加到查询结果中。这是一个我需要返回的示例

下面是两个问题

问题1

select product_id, sku from products
问题2

select product_id, sku from childproducts
结果应该是这样的。(当然没有查询1)


您可以使用UNION ALL组合它们,例如

select 1 as Sorter, product_id, sku from products
UNION ALL
select 2, product_id, sku from childproducts
ORDER BY Sorter, product_id
注意,我添加了Sorter列以使父集合显示在子产品之前。如果必须将其排除,但仍按顺序显示:

select product_id, sku
from (
    select 1 as Sorter, product_id, sku from products
    UNION ALL
    select 2, product_id, sku from childproducts
) X
ORDER BY Sorter, product_id

如果我理解正确,您希望添加一个主键来维护行的顺序,这样子行就立即跟随父行。以下代码使用
行编号()
分配新id来完成此操作:

select row_number() over (order by parentproduct_id, isparent desc) as newid,
       product_id, sku
from ((select product_id, sku, product_id as parentproduct_id, 1 as isparent
       from productions
      ) union all
      (select product_id, sku, parentproduct_id, 0 as isparent
       from childproducts
      )
     ) p
如果您实际上不想要数据中的id,而只想要排序顺序,请添加以下内容:

order by parentproduct_id, isparent desc
order by parentproduct_id, isparent desc