2017-05-30 85 views
0

您好,我有2个表,我想再加上它。计算总而言之错误的()

Table 1 --> StudentId = 1 ,Score = 10 , 20 ,30 , StudentId = 2 ,Score = 5, 5 
Table 2 --> StudentId = 1 ,Score = 5, 10 ,15 , StudentId = 2 ,Score = 15, 25 
Total = StudentId = 1 ---> 90 , StudentId = 2 ---> 45 

我使用此查询:

Select Sum(tbl_EvaPoint.Score + tbl_ActPoint.Score), 
     tbl_ActPoint.StudentId 
From tbl_EvaPoint 
JOIN tbl_ActPoint 
    ON tbl_EvaPoint.StudentId = tbl_ActPoint.StudentId 
GROUP BY tbl_ActPoint.StudentId` 

万物是确定,但我得到错误的总和,而不是90和45我得到180和90,否则somthings。

+3

你会用表格的形式来显示数据。像[** THIS **](https://senseful.github.io/web-tools/text-table/)或向我们展示什么是数据库模式,不知道该结构是什么。但通过猜测,你需要'UNION'而不是'JOIN' –

+0

你能提供输入表结构和预期输出吗? –

+0

不要在问题标题中加入“已解决”。 **接受**解决你的问题的答案。 –

回答

2

使用UNION代替JOIN

SELECT student_id, SUM(score) 
FROM (SELECT student_id, score FROM Table1 
     UNION ALL 
     SELECT student_id, score FROM Table2 
    ) as T 
GROUP BY student_id 
+0

tnx正是我想要的。我的问题解决了。 –

+0

请记住接受答案。绿色的刻度线 –

0

我认为CTE是更具可读性,但是这是个人喜好。

CREATE TABLE #S1 (
    StudentID smallint 
    ,Score smallint) 

INSERT INTO #S1 
SELECT 1, 10; 
INSERT INTO #S1 
SELECT 1, 20; 
INSERT INTO #S1 
SELECT 1, 30; 
INSERT INTO #S1 
SELECT 2, 5 
INSERT INTO #S1 
SELECT 2, 5; 

CREATE TABLE #S2 (
    StudentID smallint 
    ,Score smallint) 

INSERT INTO #S2 
SELECT 1, 5; 
INSERT INTO #S2 
SELECT 1, 10; 
INSERT INTO #S2 
SELECT 1, 15; 
INSERT INTO #S2 
SELECT 2, 15; 
INSERT INTO #S2 
SELECT 2, 25; 

WITH CTE AS (
SELECT 
    StudentID, Score 
FROM #S1 
UNION ALL 
SELECT 
    StudentID, Score 
FROM #S2) 

SELECT 
    StudentID 
    ,SUM(Score) AS TotalScore 
FROM CTE 
GROUP BY StudentID