我有表A和B
一种
+----+------+
| id | data |
+----+------+
| 1 | abc |
+----+------+
| 2 | xxx |
+----+------+
| 3 | qwe |
+----+------+
乙
+------+--------+
| a_id | rating |
+------+--------+
| 2 | 1.5 |
+------+--------+
| 2 | 5 |
+------+--------+
| 3 | 2.5 |
+------+--------+
| 1 | 3 |
+------+--------+
| 3 | 1 |
+------+--------+
现在我想从A获得的所有数据按B中的平均评分排序。
结果应为:
xxx // because the average in table B is 3.25
abc // because the average in table B is 3
qwe // because the average in table B is 1.75
我确定我必须使用诸如AVG()
和ORDER BY DESC
和子查询之类的东西,但是我不知道如何组合。
如果您使用的是SQL Server,这应该可以工作,因为您希望从A获得所有数据,所以我添加了左联接而不是内部联接。
select a.ID, a.data , avg(b.rating) Avgrating from tableA a
left join tableB b on a.ID = b.a_id
group by a.ID ,a.data
order by Avgrating desc
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句