嗨,我有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或其他的东西。
答案 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
答案 1 :(得分: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