假设我们有三个表
T1
ID |Type| Class | Points
111|1 |a101 | 12
111|1 |b104 | 10
112|2 |a112 | 40
118|1 |a245 | 30
186|2 |c582 | 23
T2(Type = 1的数据)
ID |Type|EPoints
111|1 |4
118|1 |3
T3(Type = 2的数据)
ID |Type|EPoints
112|2 |9
186|2 |15
我们希望有一个View,它将显示ID,Type,sum(Points)+ Epoints 例如
ID |Type| Points
111|1 | 26
112|2 | 49
118|1 | 33
186|2 | 38
我该怎么做?
答案 0 :(得分:0)
select dt.id
, dt.type
, dt.points + coalesce(t2.epoints, t3.epoints) as points
from (select t1.id
, t1.type
, sum(t1.points) as points
from t1
group
by t1.id) as dt
left outer
join t2
on t2.type = dt.type
left outer
join t3
on t3.type = dt.type
答案 1 :(得分:0)
看起来这可能有用(连接可能需要左边一个 - 使用围绕Epoints的COALESCE将空值转换为零 - 如果你需要对t1
中的记录采取预防措施而没有任何匹配的记录当然,在其他任何一个表中。
SELECT t1.ID, t1.Type, SUM(t1.Points) + other.Epoints
FROM t1
JOIN (
t2
UNION
t3
) other ON (other.Type = t1.Type)
GROUP BY t1.ID