Access 2007 SQL - 混合左连接和内连接

时间:2012-06-17 08:21:06

标签: sql ms-access-2007 left-join inner-join outer-join

我很难对这件事情进行排序。我已尝试过FROM部分的所有可能组合,但我似乎无法得到它。我试过逗号,混合内连接和离开加入然后这个。

[给出一些日期] 是参数提示(仅适用于MS Access 2007),因此请忽略它。

它说我的FROM部分有问题。

SELECT
    TJI.Serial AS ID,
    FIRST(TJI.Product) AS Product,
    ROUND((((SUM(TJI.JobOrder) * FIRST(TJI.ProductPackQTY)) - IIF(ISNULL(SUM(TJI.TheAmount)), 0, SUM(TJI.TheAmount))) / FIRST(TJI.STDYield)) / FIRST(TJI.MinBatch), 0) * FIRST(TJI.MinBatch) AS Batch,
    IIF(Batch <= 0, FIRST(MinBatch), Batch) AS FinalBatch

FROM TBL_JO AS TJ INNER JOIN (SELECT * FROM TBL_JOITEMS LEFT JOIN RET_STOCKS ON (Serial = TheItemSerial AND TJ.Date = TheDate) AS TJI ON TJ.Serial = TJI.JO_Serial

WHERE (TJ.Date = [give some date pls])
GROUP BY TJI.Serial

2 个答案:

答案 0 :(得分:1)

我不得不猜测你想如何在派生表上加入你的联接,但是在这些方面尝试一些东西:

SELECT
TJI.Serial AS ID,
FIRST(TJI.Product) AS Product,
ROUND((((SUM(TJI.JobOrder) * 
    FIRST(TJI.ProductPackQTY)) - 
    IIF(ISNULL(SUM(TJI.TheAmount)), 0, SUM(TJI.TheAmount))) / 
    FIRST(TJI.STDYield)) / 
    FIRST(TJI.MinBatch), 0) * FIRST(TJI.MinBatch) AS Batch,

IIF(Batch <= 0, FIRST(MinBatch), Batch) AS FinalBatch

FROM TBL_JO AS TJ
INNER JOIN (SELECT * FROM TBL_JOITEMS j
            LEFT JOIN RET_STOCKS r
            ON j.Serial =r.TheItemSerial) AS TJI 

ON TJ.Serial = TJI.JO_Serial AND TJ.Date = TJI.TheDate
GROUP BY TJI.Serial

如果您收到如上所述的错误,并且没有突出显示SQL的任何部分,则始终怀疑子查询或派生表。在这种情况下,您使用的是两个表,但您的连接未引用所涉及的表。另外,你有一个迷路支架 - ( - 在你的派生表中,它使得它无意义。

顺便说一下,使用*通常被认为是个坏主意,最好将相关字段(列)命名。

答案 1 :(得分:1)

经过一段时间的实验,我终于找到了我一直在寻找的答案。感谢你给Remou的提示和技巧。这肯定是一个很大的帮助。

我已经用RET_STOCKS交换TBL_JO而不是使用INNER JOIN,我在通过WHERE定义关系时使用了另一种方法。

SELECT JOSerial, JODate, PSerial, Product, Category, JobOrder, Yield, Pack, MinBatch, IIF(ISNULL(TheAmount),0,TheAmount) AS ReturnStocks
FROM
    (SELECT TJ.Serial AS JOSerial, TJ.Date AS JODate, TJI.Serial AS PSerial, TJI.Product AS Product, TJI.Category AS Category, TJI.JobOrder AS JobOrder, TJI.STDYield AS Yield, TJI.ProductPackQTY AS Pack, TJI.MinBatch AS MinBatch 
        FROM TBL_JO AS TJ, TBL_JOITEMS AS TJI
        WHERE TJ.Serial=TJI.JO_Serial)
AS TJX
LEFT JOIN
    RET_STOCKS AS RS
ON
    (TJX.JODate=RS.TheDate)
    AND
    (TJX.PSerial=RS.TheItemSerial)