Sql Server中的SUM显示错误

时间:2016-05-23 07:24:20

标签: sql sql-server

我在一段代码下运行

SELECT
    SUM(A.score),
    A.id,
    SUM(B.score)
FROM tableA A
INNER JOIN tableB B
    ON A.id = B.id
JOIN tableC C
    ON A.id = C.id
GROUP BY
    A.id

显示两个表中的错误总和,尤其是得分和ID的重复值。

此处的示例数据

表A

id  acore
7   100
7   300.13
7   100
7   300.13
7   300.13
7   100
7   100
7   100
7   100
7   300.13
7   300.13
7   300.13

表B

id  score
7   300.13

表C

id
7
8
9

3 个答案:

答案 0 :(得分:1)

以下查询将提供所需的结果: -

select A.id,
(select sum(A.Amt) from tableB B where B.id=A.id) AS TableA_Total,
(select sum(B.Amt) from tableB B where B.id=A.id) AS TableB_Total
from tableA A
group by A.id

答案 1 :(得分:1)

只需使用子查询从tableB获取SUM:

SELECT  A.id,
        SUM(A.amt) as score,
        B.amt
FROM tableA A
INNER JOIN (
        SELECT B.id, SUM(B.amt) as amt
        FROM tableB B
        GROUP BY b.id) as B 
        ON A.id = B.id
JOIN tableC C
    ON A.id = C.id
GROUP BY
    A.id, B.amt

输出:

7   2400.78 300.13

答案 2 :(得分:1)

请使用以下代码。它在SQL Server 2012中运行良好

DECLARE @table_A TABLE (ID int , Score float)
DECLARE @table_B TABLE (ID int , Score float)
DECLARE @table_C TABLE (ID int)

INSERT @table_A
(ID,Score)
VALUES
(7,100),
(7,300.13),
(7,100),
(7,300.13),
(7,300.13),
(7,100),
(7,100),
(7,100),
(7,100),
(7,300.13),
(7,300.13),
(7,300.13)

INSERT @table_B
(ID,Score)
VALUES
(7,300.13)

INSERT @table_C
(ID)
VALUES
(7),(8),(9)

SELECT
    A.ID,
    B.score,
    SUM(A.score) AS [Sum]
FROM @table_A A INNER JOIN @table_B B ON A.id = B.id
     INNER JOIN @table_C C ON A.id = C.id
GROUP BY
    A.id,B.score