有条件的左加入

J K*_*J K 0 sql inner-join sql-server-2008

我正在使用MS SQL。我有两个表:

1)“ OrderProducts”-此表存储订单拥有的所有产品。还有另一个Orders主表,我们可以在这张图片中省略它。订单主表存储订单的主数据,而OrderProducts表存储明细。

2)“ TransactionFeeProducts”-此表存储我要为订单收取的所有产品交易费用。它具有一个BatchID,其中多个产品可以具有相同的BatchID。

基本上,所有OrderDate介于TransactionFeeProducts.FromDate和TransactionFeeProducts.ToDate之间的订购产品都将向TransactionFeeProducts.TransactionFee收费

订购产品

  • 产品编号
  • 数量
  • 订购日期

交易费用产品

  • 批次编号
  • 产品编号
  • 从日期
  • 至今
  • 手续费

SQL:

SELECT SUM(Quantity) as Orders, 
TransactionFeeProducts.ProductID, FromDate, ToDate 
FROM TransactionFeeProducts 
LEFT JOIN OrderProducts ON TransactionFeeProducts.ProductID = OrderProducts.ProductID
WHERE
OrderDate >= TransactionFeeProducts.FromDate AND 
OrderDate <= TransactionFeeProducts.ToDate AND 
TransactionFeeProducts.BatchID = 3
GROUP BY TransactionFeeProducts.ProductID, FromDate, ToDate 
ORDER BY SUM(Quantity) DESC
Run Code Online (Sandbox Code Playgroud)

我希望SQL返回TransactionFeeProducts中的所有记录,其中BatchID =3。SUM(Quantity)应该只给我总和,即在TransactionFeeProducts.FromDate和TransactionFeeProducts.ToDate之间进行OrderDate的位置

如果SUM(Quantity)为0,则该字段应为NULL或0。

我现在的问题是,如果SUM(Quantity)为0,则SQL不返回任何记录。

请帮忙。非常感谢你。

Adr*_*der 6

将JOIN条件更改为类似

SELECT  SUM(Quantity) as Orders,  
        TransactionFeeProducts.ProductID, 
        FromDate, 
        ToDate  
FROM    TransactionFeeProducts LEFT JOIN 
        OrderProducts   ON  TransactionFeeProducts.ProductID = OrderProducts.ProductID 
                        AND OrderDate >= TransactionFeeProducts.FromDate 
                        AND OrderDate <= TransactionFeeProducts.ToDate 
WHERE   TransactionFeeProducts.BatchID = 3 
GROUP BY    TransactionFeeProducts.ProductID, 
            FromDate, 
            ToDate  
ORDER BY    SUM(Quantity) DESC
Run Code Online (Sandbox Code Playgroud)

所不同的是,如果您将过滤条件的WHERE条款会影响查询过滤一样,如果你使用的INNER JOIN,说明你将只包括条目TransactionFeeProducts,其中OrderDate >= TransactionFeeProducts.FromDate and OrderDate <= TransactionFeeProducts.ToDate

看下面的例子

DECLARE @TABLE1 TABLE(
        ID INT,
        FromDate DATETIME,
        ToDate DATETIME
)

INSERT INTO @TABLE1 SELECT 1, '01 Jan 2012','31 Jan 2012'

DECLARE @TABLE2 TABLE(
        ID INT,
        DateValue DATETIME
)

INSERT INTO @TABLE2 SELECT 1, '01 Feb 2012'

SELECT  *
FROM    @TABLE1 t1 LEFT JOIN
        @TABLE2 t2  ON  t1.ID = t2.ID
                    AND t2.DateValue BETWEEN t1.FromDate AND t1.ToDate

SELECT  *
FROM    @TABLE1 t1 LEFT JOIN
        @TABLE2 t2 ON   t1.ID = t2.ID
WHERE   t2.DateValue BETWEEN t1.FromDate AND t1.ToDate
Run Code Online (Sandbox Code Playgroud)

选择1说:

返回T1的所有行,仅返回T2的所有行,其中 t1.ID = t2.ID AND t2.DateValue BETWEEN t1.FromDate AND t1.ToDate

另一方面,选择2表示:

仅返回T1中的所有行t1.ID = t2.ID,然后返回T1中的所有行,然后仅返回其中的行t2.DateValue BETWEEN t1.FromDate AND t1.ToDate

SQL SERVER – JOIN的介绍– JOIN的基本知识总是很容易掌握。