2014-07-24 135 views
0

我有三個表,我需要從表學生的代碼列中總結表薪和薪酬2的字段。
我寫了一個查詢,但第一個表(這裏是表支付)是正確的答案,但第二個表(這裏是表pay2)是每個記錄重複到第一個表記錄計數和答案是錯誤的!總結來自三個表的字段

SELECT DISTINCT STUDENTS.CODE, 
       STUDENTS.NAME, 
       Sum(Cast (PAY.PRICE AS INT)) AS payTotal, 
       Sum(Cast (PAY2.PRICE AS INT)) AS pay2Total 
FROM STUDENTS 
     LEFT OUTER JOIN PAY 
        ON STUDENTS.CODE = PAY.CODE 
     LEFT OUTER JOIN PAY2 
        ON STUDENTS.CODE = PAY2.CODE 
GROUP BY STUDENTS.CODE, 
      STUDENTS.NAME 

回答

0

你可以這樣做:

SELECT 
    students.code, 
    students.name, 
    (
     SELECT 
      SUM(cast (pay.price AS INT)) 
     FROM 
      pay 
     WHERE 
      students.code=pay.code 
    ) AS payTotal, 
    (
     SELECT 
      SUM(cast(pay2.price AS INT)) 
     FROM 
      pay2 
     WHERE 
      students.code=pay2.code 
    ) AS pay2Total 
FROM 
    students