访问SQL LEFT JOIN替代方案

时间:2016-08-11 13:38:49

标签: sql ms-access left-join access

我正在使用LEFT JOIN通过SQL尝试Access,但它似乎不起作用。 Access不断生成错误“不支持JOIN表达式。”。

我想要完成的工作如下。我有一张带工作卡的桌子和另一张桌子,费用如下。

JOBCARDS
ID    JOBNAME
1     Job one
2     Job two
3     Job three

COSTS
ID    TYPE    COST    JOB
1     PART    15.01   1
2     LABOUR  20.00   1
3     LABOUR  40.00   2
4     PART    34.54   3
5     PART    84.67   3

我正在尝试制定一个SQL查询,它会给我以下结果:

QUERY
ID    JOBNAME    PARTS    LABOUR
1     Job one    15.01    20.00
2     Job two    0.00     40.00
3     Job three  119.21   0.00

我想出了什么:

SELECT
    CARDS.[ID] AS [ID],
    CARDS.[JOBNAME] AS [JOBNAME],
    SUM (COSTS1.[COST]) AS [PARTS],
    SUM (COSTS2.[COST]) AS [LABOUR]
FROM
    (([JOBCARDS] CARDS LEFT JOIN [COSTS] COSTS1 ON COSTS1.[JOB]=CARDS.[ID] AND COSTS1.[TYPE]='PART')
    LEFT JOIN [COSTS] COSTS2 ON COSTS2.[JOB]=CARDS.[ID] AND COSTS2.[TYPE]='LABOUR')
GROUP BY
    CARDS.[ID], CARDS.[JOBNAME];

访问似乎与“COSTS1。[TYPE] ='PART'”部分有问题。

有没有办法在不使用LEFT JOIN的情况下完成我想要做的事情? 或者有人发现错误吗?

2 个答案:

答案 0 :(得分:2)

这个SQL会给出结果。
0值将为Null,但您可以使用NZ将其替换为0。

SELECT      JobCards.ID
            ,JobName
            ,SUM(C2.Cost) AS Parts
            ,SUM(C1.Cost) AS Labour
FROM        (JobCards LEFT JOIN Costs C1 ON (JobCards.ID = C1.Job AND C1.Type = 'Labour'))
                      LEFT JOIN Costs C2 ON (JobCards.ID = C2.Job AND C2.Type = 'Part')
GROUP BY    JobCards.ID
            ,JobName

修改 重新阅读你的SQL - 你只是忘了把括号放在你的Join中的ON语句之后:
(COSTS1.[JOB]=CARDS.[ID] AND COSTS1.[TYPE]='PART')

SELECT
    CARDS.[ID] AS [ID],
    CARDS.[JOBNAME] AS [JOBNAME],
    SUM (COSTS1.[COST]) AS [PARTS],
    SUM (COSTS2.[COST]) AS [LABOUR]
FROM
    (([JOBCARDS] CARDS LEFT JOIN [COSTS] COSTS1 ON (COSTS1.[JOB]=CARDS.[ID] AND COSTS1.[TYPE]='PART'))
    LEFT JOIN [COSTS] COSTS2 ON (COSTS2.[JOB]=CARDS.[ID] AND COSTS2.[TYPE]='LABOUR'))
GROUP BY
    CARDS.[ID], CARDS.[JOBNAME];

编辑2 :没有必要在所有内容中放置括号,或者如果字段名与源字段相同,则使用别名,或者使用SELECT中的表名称&安培; WHERE子句除非字段名称出现在多个表中。

答案 1 :(得分:1)

以下是相关的子查询示例:

SELECT JOBCARDS.ID, 
       JOBCARDS.JOBNAME, 
       (SELECT SUM([COST]) FROM COSTS WHERE COSTS.JOB = JOBCARDS.ID AND COSTS.TYPE = 'PART') AS PARTS, 
       (SELECT SUM([COST]) FROM COSTS WHERE COSTS.JOB = JOBCARDS.ID AND COSTS.TYPE = 'LABOUR') AS LABOUR
FROM JOBCARDS;