左连接和从表计数
Left join and Count from tables
我有 3 table
Table Ploeg 与
PloegID | Name |
5 | name1|
2 | name2|
Table 四舍五入
ID | PloegID | Timestamp
1 | 5 | xxxxxx
2 | 2 | xxxxxx
3 | 5 | xxxxxx
4 | 5 | xxxxxx
5 | 2 | xxxxxx
Table 平均值为
ID | PloegID | Speed
1 | 5 | 4
2 | 2 | 3
3 | 5 | 6
4 | 5 | 2
5 | 2 | 3
我需要的是 table 和
PloegID | Average of Speed for each ploegID | Name | Count of Ploegid in table Round.
5 | 6 | name1 | 3
2 | 3 | name2 | 2
我有这段代码,但它计算的轮次有误
SELECT g.ploegid, AVG(g.speed) as average,l.name ,count(r.ploegid) AS rondes
FROM averages as g
left join Ploeg as l on l.id = g.ploegid
left join Round as r on r.ploegid = l.ploegid
GROUP BY ploegid
ORDER BY g.ploegid;
速度正确,但计数不正确。
每个 table 中可能有多行与 ploegid
匹配。因此,您得到的笛卡尔积会导致计算失败。我还建议您以 Ploeg
开始 left join
s,因为这似乎是驱动 table:
SELECT l.ploegid, g.average, l.name, r.rondes
FROM Ploeg l left join
(select ploegid, avg(g.speed) as average
from averages g
group by ploegid
) g
on l.id = g.ploegid left join
(select ploegid, count(*) as rondes
from Round r
group by ploegid
) r
on r.ploegid = l.ploegid
ORDER BY l.ploegid;
我有 3 table
Table Ploeg 与
PloegID | Name |
5 | name1|
2 | name2|
Table 四舍五入
ID | PloegID | Timestamp
1 | 5 | xxxxxx
2 | 2 | xxxxxx
3 | 5 | xxxxxx
4 | 5 | xxxxxx
5 | 2 | xxxxxx
Table 平均值为
ID | PloegID | Speed
1 | 5 | 4
2 | 2 | 3
3 | 5 | 6
4 | 5 | 2
5 | 2 | 3
我需要的是 table 和
PloegID | Average of Speed for each ploegID | Name | Count of Ploegid in table Round.
5 | 6 | name1 | 3
2 | 3 | name2 | 2
我有这段代码,但它计算的轮次有误
SELECT g.ploegid, AVG(g.speed) as average,l.name ,count(r.ploegid) AS rondes
FROM averages as g
left join Ploeg as l on l.id = g.ploegid
left join Round as r on r.ploegid = l.ploegid
GROUP BY ploegid
ORDER BY g.ploegid;
速度正确,但计数不正确。
每个 table 中可能有多行与 ploegid
匹配。因此,您得到的笛卡尔积会导致计算失败。我还建议您以 Ploeg
开始 left join
s,因为这似乎是驱动 table:
SELECT l.ploegid, g.average, l.name, r.rondes
FROM Ploeg l left join
(select ploegid, avg(g.speed) as average
from averages g
group by ploegid
) g
on l.id = g.ploegid left join
(select ploegid, count(*) as rondes
from Round r
group by ploegid
) r
on r.ploegid = l.ploegid
ORDER BY l.ploegid;