如何在SQL Server中组合两个select语句

时间:2013-12-26 16:17:32

标签: sql sql-server

我需要将两个select语句组合成单个select语句

选择#1:

 SELECT 
    Product_Name as [Product Name], Product_Id as [Product Id]
 from 
    tb_new_product_Name_id
 where  
    Product_Name LIKE '%' + @product_name_id + '%' 
    or Product_Id like '%' + @product_name_id + '%' ;

选择#2:

SELECT 
    COUNT(Product_id) + 1 as duplicate_id
FROM 
    tb_new_product_Name_id_duplicate
WHERE 
    Product_id = (SELECT  Product_id
                  FROM tb_new_product_Name_id
                  WHERE Product_Name = @product_name_id);

如何将上述两个查询组合成单个select语句。我需要显示三列duplicate_id,[产品名称],[产品ID]。谢谢..

3 个答案:

答案 0 :(得分:1)

您可以使用subquery获得所需的结果

SELECT 
    Product_Name as [Product Name], Product_Id as [Product Id],(SELECT 
    COUNT(Product_id) + 1 as duplicate_id FROM 
    tb_new_product_Name_id_duplicate
    WHERE 
    Product_id = (SELECT  Product_id
                  FROM tb_new_product_Name_id
                  WHERE Product_Name = @product_name_id)) as duplicate_id 
 from 
    tb_new_product_Name_id
 where  
    Product_Name LIKE '%' + @product_name_id + '%' 
    or Product_Id like '%' + @product_name_id + '%' ;

答案 1 :(得分:0)

这是你想要的吗?

SELECT COUNT(Product_id)+1 as duplicate_id
FROM tb_new_product_Name_id_duplicate
WHERE Product_id= (SELECT  Product_id
                   FROM tb_new_product_Name_id
                   WHERE Product_Name LIKE '%'+@product_name_id+'%' or
                         Product_Id like '%'+@product_name_id+'%'
                 );

答案 2 :(得分:0)

我认为这就是你要找的东西

SELECT A.Product_Name AS [Product Name], A.Product_Id AS [Product Id], B.duplicate_id
FROM tb_new_product_Name_id AS A, 
(
    SELECT COUNT(Product_id)+1 AS duplicate_id
    FROM tb_new_product_Name_id_duplicate
    WHERE Product_id= (SELECT  Product_id
                       FROM tb_new_product_Name_id
                       WHERE Product_Name=@product_name_id
                     )
) AS B
WHERE  A.Product_Name LIKE '%'+@product_name_id+'%' OR Product_Id like '%'+@product_name_id+'%';