SQL Server,如何在一个表中创建两个select语句

时间:2016-05-12 18:08:30

标签: sql-server

我使用不同的结果集制作两个select语句, 请帮我把这两个select语句显示在一个表中,

DECLARE @EmpID INT

SELECT @EmpID = SubCategoryId
FROM dbo.Product
WHERE ProductId = 13

SELECT Product.ProductId
    , Product.ProductName
    , Product.ProductPrice
    , Product.ProductQuantity
    , Product.SubCategoryId AS ForUpdate
    , SubCategory.SubCategoryName
    , SubCategory.SubCategoryId
FROM Product
INNER JOIN ProductUnderCategory
    ON ProductUnderCategory.ProductId = Product.ProductId
INNER JOIN SubCategory
    ON ProductUnderCategory.SubCategoryId = SubCategory.SubCategoryId
WHERE Product.ProductId = 13

SELECT Property.Propertyid
    , Property.PropertyName
    , ProductProperties.PropertyValue
FROM Property
LEFT JOIN ProductProperties
    ON Property.PropertyId = ProductProperties.PropertyId AND ProductProperties.ProductId = 13
WHERE Property.Propertyid IN (
        SELECT PropertyId
        FROM CategoryProperty
        WHERE CategoryProperty.SubCategoryId = CategoryProperty.SubCategoryId AND CategoryProperty.SubCategoryId = @EmpID
        )

2 个答案:

答案 0 :(得分:0)

您可能会执行以下操作 - 如果第一个选择中不存在列,则需要包含适当的值,并且必须为列命名。如果后续选择中不存在列,则只需返回null /'' / 0或任何您需要的值作为值;

select Product.ProductId, Product.ProductName, Product.ProductPrice, Product.ProductQuantity,  '' as someColumn,  ....
from ....
union [all]
Select   Property.Propertyid,  Property.PropertyName,    ProductProperties.PropertyValue,  NULL (for ProductQuantity), ProductProperties.someColumn
from .....

答案 1 :(得分:0)

我假设你想要每个产品的属性(不是联合,而是联接)。像这样:

DECLARE @EmpID INT

SELECT @EmpID = SubCategoryId
FROM dbo.Product
WHERE ProductId = 13

SELECT Product.ProductId
    , Product.ProductName
    , Product.ProductPrice
    , Product.ProductQuantity
    , Product.SubCategoryId AS ForUpdate
    , SubCategory.SubCategoryName
    , SubCategory.SubCategoryId
    , Property.Propertyid
    , Property.PropertyName
    , ProductProperties.PropertyValue
FROM Product
INNER JOIN ProductUnderCategory
    ON ProductUnderCategory.ProductId = Product.ProductId
INNER JOIN SubCategory
    ON ProductUnderCategory.SubCategoryId = SubCategory.SubCategoryId
LEFT JOIN ProductProperties
    on ProductProperties.ProductID = Product.ProductID
left join Property
    ON Property.PropertyId = ProductProperties.PropertyId 
    and Property.Propertyid IN (
        SELECT PropertyId
            FROM CategoryProperty
            WHERE 
              CategoryProperty.SubCategoryId = CategoryProperty.SubCategoryId
              AND CategoryProperty.SubCategoryId = @EmpID
            )
WHERE Product.ProductId = 13