如何在MS Access中创建具有多个条件的SQL查询

时间:2018-03-24 19:25:47

标签: sql ms-access

请帮我解释以下语法。它出了问题...

我有两个表,表1读者和表2贷款。

我想返回有关来自NB_Readers最多的readerID readerid的所有信息......

SELECT Surname, Name, Phone, Address, E-mail 
FROM Readers 
INNER JOIN (SELECT TOP 1 * 
            FROM
                (SELECT ReaderID, COUNT (readerID) as NB_Readers
                 FROM Loans AS W
                 WHERE (YEAR(loans.datefrom) = 2018 
                   AND YEAR(loans.dateto) = 2018)
                 GROUP BY readerid)
            ORDER BY NB_Readers DESC) ON Readers.ReaderID = W.ReaderID

1 个答案:

答案 0 :(得分:0)

您的代码问题是作用域之一:在最外层的join子句中,您引用了表W,但是,此别名是在最内层的嵌套SELECT查询中分配的,并且不存在在此查询之外。

使代码能够工作的最简单修改是将别名分配从嵌套的SELECT查询移动到您要与Readers表连接的查询,即:

SELECT Surname, Name, Phone, Address, E-mail 
FROM Readers 
INNER JOIN 
(
    SELECT TOP 1 * 
    FROM
    (
        SELECT ReaderID, COUNT (ReaderID) as NB_Readers
        FROM Loans
        WHERE (YEAR(datefrom) = 2018 AND YEAR(dateto) = 2018)
        GROUP BY ReaderID
    )
    ORDER BY NB_Readers DESC
) AS W
ON Readers.ReaderID = W.ReaderID