在SELECT查询

时间:2015-05-19 21:04:36

标签: sql ms-access

我一直在努力让这个访问查询正常工作,我正在学习编写SQL,所以我想尝试使用别名来使我的表格更容易使用但是对于某些人来说我不断收到错误的原因。这是我原来的SQL查询

SELECT qryCurrentMonthMtrHis.Utility
    ,qryCurrentMonthMtrHis.MeterID
    ,qryLastYearAvgMtrHis.AvgOfUnits AS LYRAvgOfUnits
    ,qryLastYearMtrHis.Units AS LYRUnits
    ,qryLastMonthMtrHis.Units AS PrevMonUnits
    ,qryCurrentMonthMtrHis.Units AS CurrentUnits
    ,qryLastYearAvgMtrHis.AvgOfTotCost
    ,qryLastYearMtrHis.TotCost AS LYRTotCost
    ,qryLastMonthMtrHis.TotCost AS PrevMonTotCost
    ,qryCurrentMonthMtrHis.TotCost AS CurrentTotCost
FROM qryLastYearMtrHis
RIGHT JOIN (
    qryLastYearAvgMtrHis RIGHT JOIN (
        qryLastMonthMtrHis RIGHT JOIN qryCurrentMonthMtrHis ON (qryLastMonthMtrHis.Utility = qryCurrentMonthMtrHis.Utility)
            AND (qryLastMonthMtrHis.MeterID = qryCurrentMonthMtrHis.MeterID)
        ) ON (qryLastYearAvgMtrHis.Utility = qryCurrentMonthMtrHis.Utility)
        AND (qryLastYearAvgMtrHis.MeterID = qryCurrentMonthMtrHis.MeterID)
    ) ON (qryLastYearMtrHis.Utility = qryCurrentMonthMtrHis.Utility)
    AND (qryLastYearMtrHis.MeterID = qryCurrentMonthMtrHis.MeterID);

以下是我尝试使用别名

的问题
    SELECT cm.Utility
    ,cm.MeterID
    ,lyra.AvgOfUnits AS LYRAvgOfUnits
    ,lyr.Units AS LYRUnits
    ,pm.Units AS PrevMonUnits
    ,cm.Units AS CurrentUnits
    ,lyra.AvgOfTotCost
    ,lyr.TotCost AS LYRTotCost
    ,pm.TotCost AS PrevMonTotCost
    ,cm.TotCost AS CurrentTotCost
FROM qrylastYearMtrHis lyr
RIGHT JOIN (
    qryLastYearAvgMtrHis lyra RIGHT JOIN (
        qryLastMonthMtrHis pm RIGHT JOIN qryCurrentMonthMtrHis cm ON (lyr.Utility = cm.Utility)
            AND (pm.MeterID = cm.MeterID)
        ) ON (lyra.Utility = cm.Utility)
        AND (lyra.MeterID = cm.MeterID)
    ) ON (lyr.Utility = cm.Utility)
    AND (lyr.MeterID = cm.MeterID);

当我尝试运行第二个时,它表示"连接操作中的语法错误"并突出了" lyr"在lyra.AvgOfUnits。从我在网上看到它应该有效,所以我想知道是否有人可以提供任何见解?

2 个答案:

答案 0 :(得分:2)

您在联接中使用了错误的别名:

RIGHT JOIN (
    qryLastYearAvgMtrHis lyra RIGHT JOIN (
        qryLastMonthMtrHis pm RIGHT JOIN qryCurrentMonthMtrHis cm ON (lyr.Utility = cm.Utility)

必须是pm.Utility而不是lyr.Utility

您没有使用搜索和替换吗?

答案 1 :(得分:1)

SELECT cm.Utility, cm.MeterID, lyra.AvgOfUnits AS LYRAvgOfUnits, lyr.Units AS LYRUnits,
       pm.Units AS PrevMonUnits, cm.Units AS CurrentUnits, lyra.AvgOfTotCost, 
       lyr.TotCost AS LYRTotCost, pm.TotCost AS PrevMonTotCost, 
       cm.TotCost AS CurrentTotCost
FROM qryLastYearMtrHis lyr 
RIGHT JOIN (qryLastYearAvgMtrHis lyra 
    RIGHT JOIN (qryLastMonthMtrHis pm 
        RIGHT JOIN qryCurrentMonthMtrHis cm ON (pm.Utility = cm.Utility) 
                                            AND (pm.MeterID = cm.MeterID))
        ON (lyra.Utility = cm.Utility) AND (lyra.MeterID = cm.MeterID)) 
ON (lyr.Utility = cm.Utility) AND (lyr.MeterID = cm.MeterID);