0

如何在 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)
4

2 回答 2

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
于 2012-09-30T23:00:30.723 回答
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
于 2012-09-30T23:06:13.950 回答