我想将表1和2合并到表3中。我需要对表1中的行进行分组以匹配表2的格式,同时将每个范围的c1,c2和c3相加。
我对联接的理解很薄弱,可以得到帮助。
表1:
ID begin end c1 c2 c3
78JUE 20 24 1 0 0
78JUE 24 28 2 1 0
78JUE 28 32 1 1 0
78JUE 32 36 0 0 0
78JUE 36 40 0 0 0
78JUE 40 44 4 1 1
78JUE 44 48 3 1 1
78JUE 48 52 1 2 0
78JUE 52 56 0 1 1
78JUE 56 60 2 0 1
78JUE 60 64 1 1 0
78JUE 64 68 0 2 1
表2:
ID begin end
78JUE 20 40
78JUE 40 52
78JUE 52 60
78JUE 60 68
表3:
ID begin end c1 c2 c3
78JUE 20 40 4 2 0
78JUE 40 52 8 4 2
78JUE 52 60 2 1 2
78JUE 60 68 1 3 1
答案 0 :(得分:0)
嗨,应该这样做:
SELECT
T1.ID
,T1.begin
,T1.end
,SELECT(SUM(T2.c1) FROM Table2 T2 WHERE T2.ID = T1.ID AND T2.begin >= T1.begin AND T2.end <= T1.end) c1
,SELECT(SUM(T2.c2) FROM Table2 T2 WHERE T2.ID = T1.ID AND T2.begin >= T1.begin AND T2.end <= T1.end) c2
,SELECT(SUM(T2.c3) FROM Table2 T2 WHERE T2.ID = T1.ID AND T2.begin >= T1.begin AND T2.end <= T1.end) c3
FROM Table1 T1