总结三个表中的字段

时间:2014-07-24 10:59:44

标签: sql-server

我有三张桌子,我需要从表格学生的表格栏中汇总表格付款和付款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 

1 个答案:

答案 0 :(得分: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