SQL:如何按联盟

时间:2016-11-01 20:40:39

标签: sql sql-server

我对SQl很陌生,所以我不确定如何构建谷歌搜索的问题。基本上,我试图联合两组专栏。他们有非常相似的信息;集合A是一系列产品,其中包含供应商的列。 B组是一系列没有供应商的产品。

我想要做的是过滤器集A,只显示某个供应商的产品(这是我对WHERE子句所做的)。但是,我想联合Set A和Set B,这样Set B中的值将只显示(和组合)产品的Set A中有一个条目。

也就是说,为了更好地解释,我希望Set B能够看到'设置A.它将看到集合A仅包含来自某个供应商的项目,而集合B将删除集合A不具有的项目(不是来自该供应商的项目)。

有什么想法?谢谢,

以下代码:

SELECT ([Transfer_From]
      ,'Transfer_To' = [WAREHOUSE_CODE]
      ,'Product_Number' = [PRODUCT_NUMBER]
      ,'QTY_Trans' = [quantity_received]
      ,'Transfer_Date' = [received_date]

  FROM [fstrkdb_1].[dbo].[Inventry]
  WHERE vendor_number = '1074'

UNION

SELECT [Transfer_From]
        ,[Transfer_To]
      ,[Product_Number]
      ,'QTY_Trans' =[Quantity_Allocated]
      ,[Transfer_Date]

  FROM [fstrkdb_1].[dbo].[InvtransFromWhs]


ORDER BY Transfer_Date

GO

2 个答案:

答案 0 :(得分:2)

一种方法是在EXISTS子句中使用WHERE。 CTE有助于避免重复第一个查询:

WITH a as (
      SELECT Transfer_From, WAREHOUSE_CODE as Transfer_To, Product_Number,
             quantity_received as QTY_Trans, received_date as Transfer_Date
      FROM [fstrkdb_1].[dbo].[Inventry]
      WHERE vendor_number = '1074'
     )
SELECT a.*
FROM a
UNION ALL
SELECT Transfer_From, Transfer_To, Product_Number, Quantity_Allocated
       Transfer_Date
FROM [fstrkdb_1].[dbo].InvtransFromWhs ifw
WHERE EXISTS (SELECT 1 FROM a WHERE a.Product_Number = ifw.Product_Number)
ORDER BY Transfer_Date;

如果您希望重复,则只需UNION。查询不应该创建意外的重复项。

答案 1 :(得分:1)

WITH DataSet1 as (
SELECT ([Transfer_From]
      ,'Transfer_To' = [WAREHOUSE_CODE]
      ,'Product_Number' = [PRODUCT_NUMBER]
      ,'QTY_Trans' = [quantity_received]
      ,'Transfer_Date' = [received_date]

  FROM [fstrkdb_1].[dbo].[Inventry]
  WHERE vendor_number = '1074'),
DataSet2 as (

SELECT [Transfer_From]
        ,[Transfer_To]
      ,[Product_Number]
      ,'QTY_Trans' =[Quantity_Allocated]
      ,[Transfer_Date]

  FROM [fstrkdb_1].[dbo].[InvtransFromWhs] A
  INNER JOIN dataset1 B
   on A.Product_number = B.Product_number)

SELECT * FROM dataset1
UNION 
SELECT * FROM dataset2
ORDER BY Transfer_Date

这样做会产生dataset1。然后使用dataset1中的产品作为dataset2的过滤器,然后将这两个集合在一起。