2017-04-20 152 views
0

我有一個表,用於存儲代理的詳細信息,這看起來如下:SQL連接查詢在MS Access

AgentTable

在另一張表,我有如下所示的稅率信息:

TaxTable

我需要在2張桌子上執行一個查詢,其中顯示代理人的姓名,他們根據納稅檔案支付的稅款總額以及他們的工資,他們的主管的姓名和d主管人員根據納稅標準和他們的工資支付的稅額。查詢的目的是表明,由於稅率的百分比,主管人員支付的稅額要比下屬多得多。

這是迄今爲止我已經制定了查詢:

Select A.AgentName AS AgentName, 
((A.Salary)*(Select S.PlusPercentage FROM TaxBracket AS S WHERE A.Salary >=S.FromEarnings AND A.Salary <= S.ToEarnings) + S.BasicTax) AS "Tax Paid By Agent" , 
B.AgentName AS "Supervisor", 
((B.Salary)*(Select T.PlusPercentage FROM TaxBracket AS T WHERE A.Salary >=T.FromEarnings AND A.Salary <= T.ToEarnings) + T.BasicTax) AS "Tax Paid By Supervisor" , 
FROM Agent AS 'A', TaxBracket AS 'S', Agent AS 'B', TaxBracket AS 'T' 
WHERE A.Supervisor = B.AgentNo 
AND A.Commission IS NULL, 
ORDER BY A.AgentName DESC 

我得到它規定一個錯誤「select語句包含保留字或拼寫錯誤或缺少變量名,或標點符號不正確「。

我不確定這個錯誤發生在哪裏,任何人都可以請幫忙嗎?

+1

跟蹤我的注意力的第一件事是,你引用你的表別名,如'A'。在Access中這是必需的(不知道)。因爲在SQL中,這是行不通的。您是否嘗試過在刪除此引號時有效? – Kevin

+0

@Kevin我不認爲這是必要的,但它在MS Access中是有效的 –

+0

您在SELECT子句中的最後一個字段之後也有一個逗號,...... AS「由主管負責的稅」FROM。再次在SQL中,這是不正確的。我還會在ORDER BY子句前面看到另一個逗號。也許你可以刪除這些並再試一次。 – Kevin

回答

2

有你的SQL的幾個問題:

有一個在你的SELECT(刪除逗號)結束逗號

T.BasicTax) AS "Tax Paid By Supervisor" , 
FROM 

有一個在你從結束一個逗號(除去逗號)

AND A.Commission IS NULL, 
ORDER BY 

您的表別名不應被包裹(去掉引號)

Agent AS 'A', TaxBracket AS 'S', Agent AS 'B', TaxBracket AS 'T' 

對於字段名稱,使用方括號(去掉引號,以 '[' 和 ']' 代替)

AS "Tax Paid By Agent", 
AS [Tax Paid By Agent], 

固定:

SELECT 
    A.AgentName AS AgentName, 
    (
     (A.Salary) * (
      SELECT 
       S.PlusPercentage 
      FROM 
       TaxBracket AS S 
      WHERE 
       A.Salary >= S.FromEarnings 
      AND A.Salary <= S.ToEarnings 
     ) + S.BasicTax 
    ) AS [Tax Paid By Agent], 
    B.AgentName AS [Supervisor], 
    (
     (B.Salary) * (
      SELECT 
       T.PlusPercentage 
      FROM 
       TaxBracket AS T 
      WHERE 
       A.Salary >= T.FromEarnings 
      AND A.Salary <= T.ToEarnings 
     ) + T.BasicTax 
    ) AS [Tax Paid By Supervisor] 
FROM 
    Agent AS A, 
    TaxBracket AS S, 
    Agent AS B, 
    TaxBracket AS T 
WHERE 
    A.Supervisor = B.AgentNo 
    AND A.Commission IS NULL 
ORDER BY 
    A.AgentName DESC 

如果你想要的東西有點簡單,也許嘗試這樣的事情:

SELECT 
    a.AgentName, 
    a.Salary, 
    (SELECT a.Salary*([PlusPercentage])+t.BasicTax AS tax FROM TaxBracket AS t WHERE t.FromEarnings<=a.Salary AND t.ToEarnings>=a.Salary;) AS aTax, 
    s.AgentName AS Supervisor, 
    s.Salary, 
    (SELECT s.Salary*([PlusPercentage])+t.BasicTax AS tax FROM TaxBracket AS t WHERE t.FromEarnings<=s.Salary AND t.ToEarnings>=s.Salary;) AS sTax 
FROM Agent AS a LEFT JOIN Agent AS s ON a.Supervisor = s.AgentNo;