添加主行以查询结果

时间:2012-09-30 22:53:48

标签: sql sql-server-2005

如何在MSSQL 2005中向查询结果添加主行。以下是我需要返回的示例?

以下是两个查询

查询1

select product_id, sku from products

查询2

select product_id, sku from childproducts

结果应如下所示。 (当然没有查询1)

    row 1: products.product_id, products.sku   (comes from one parent table)
    row 2: childproducts.product_id, childproducts.sku   (comes from child table)
    row 3: childproducts.product_id, childproducts.sku   (comes from child table)

2 个答案:

答案 0 :(得分:0)

您可以使用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

答案 1 :(得分:0)

如果我理解正确,您希望添加一个维持行排序的主键,以便子项紧跟父项。以下代码使用row_number()来分配新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