SQL选择两个条件的位置

时间:2017-03-24 18:10:51

标签: sql database vb.net

我有三个表,例如:How to join three tables to get Sum

我已将字段日期添加到购买和Invoce表中,并过滤所有购买并将次要文件作为参数提供给vb:

SELECT P.Product_no, Inv.InvProdSum, Pur.PurProdSum
FROM Product P
LEFT JOIN (SELECT Product_no, SUM(Qty) AS InvProdSum
          FROM Invoice 
          WHERE date < @DateParameter
          GROUP BY Product_no) AS Inv
ON P.Product_no = Inv.Product_no
LEFT  JOIN (SELECT Product_no, SUM(Qty) AS PurProdSum
            FROM Purchase 
            WHERE date < @DateParameter
            GROUP BY Product_no) AS Pur
ON P.Product_no = Pur.Product_no

我还想在结果表中再添两列:发票总额和购买总和,其中date = @DateParameter。例如,我的目标是获取日期是2017年1月27日,即该日期之前的购买总和和仅1月购买的总和,以及作为参数提供的任何日期。同样对于invoce。  对不起我的英文

1 个答案:

答案 0 :(得分:1)

使用不同条件向具有不同条件的相同表添加其他连接以获得所需内容:

SELECT P.Product_no, Inv.InvProdSum, Pur.PurProdSum. InvCurrent.InvProdSum AS [CurrentInvoiceProdSum], PurCurrent.PurProdSum AS [CurrentProductSum]
FROM Product P
LEFT JOIN (SELECT Product_no, SUM(Qty) AS InvProdSum
          FROM Invoice 
          WHERE date < @DateParameter
          GROUP BY Product_no) AS Inv
ON P.Product_no = Inv.Product_no
LEFT  JOIN (SELECT Product_no, SUM(Qty) AS PurProdSum
            FROM Purchase 
            WHERE date < @DateParameter
            GROUP BY Product_no) AS Pur
ON P.Product_no = Pur.Product_no
LEFT JOIN (SELECT Product_no, SUM(Qty) AS InvProdSum
          FROM Invoice 
          WHERE date = @DateParameter
          GROUP BY Product_no) AS InvCurrent
ON P.Product_no = InvCurrent.Product_no
LEFT  JOIN (SELECT Product_no, SUM(Qty) AS PurProdSum
            FROM Purchase 
            WHERE date = @DateParameter
            GROUP BY Product_no) AS PurCurrent
ON P.Product_no = PurCurrent.Product_no

如果违反交易表只是性能损失太大,您可以尝试获取初始结果 包括当前和过去的值,然后从中查询:

SELECT Product_no, Qty AS InvProdSum
INTO #tmpInvoice
FROM Invoice 
WHERE date <= @DateParameter

SELECT Product_no, Qty AS PurProdSum
INTO #tmpPurchase
FROM Purchase 
WHERE date <= @DateParameter

SELECT P.Product_no, Inv.InvProdSum, Pur.PurProdSum. InvCurrent.InvProdSum AS [CurrentInvoiceProdSum], PurCurrent.PurProdSum AS [CurrentProductSum]
FROM Product P
LEFT JOIN (SELECT Product_no, SUM(Qty) AS InvProdSum
          FROM #tmpInvoice 
          WHERE date < @DateParameter
          GROUP BY Product_no) AS Inv
ON P.Product_no = Inv.Product_no
LEFT  JOIN (SELECT Product_no, SUM(Qty) AS PurProdSum
            FROM #tmpPurchase 
            WHERE date < @DateParameter
            GROUP BY Product_no) AS Pur
ON P.Product_no = Pur.Product_no
LEFT JOIN (SELECT Product_no, SUM(Qty) AS InvProdSum
          FROM #tmpInvoice 
          WHERE date = @DateParameter
          GROUP BY Product_no) AS InvCurrent
ON P.Product_no = InvCurrent.Product_no
LEFT  JOIN (SELECT Product_no, SUM(Qty) AS PurProdSum
            FROM #tmpPurchase 
            WHERE date = @DateParameter
            GROUP BY Product_no) AS PurCurrent
ON P.Product_no = PurCurrent.Product_no