当前位置:Gxlcms > PHP教程 > 还是问一个mysql的查询汇总的汇总有关问题

还是问一个mysql的查询汇总的汇总有关问题

时间:2021-07-01 10:21:17 帮助过:5人阅读

还是问一个mysql的查询汇总的汇总问题
本帖最后由 setoy 于 2013-12-18 18:11:02 编辑

有五个人,uid分别是1~5
有对着这五个人打分的表格(某个人有可能没有得到过分数)
id  uid  scroe
-------------
1 1 1.5
2 1 1.8
3 2 -5.5
4 1 0.8
5 2 8.2
6 1 -2
7 4 3
8 2 2.3
--------------


现在要统计他们所有人的分数,即使查询不到某个人的得分,也要显示0分,显示格式如下:
用户  分数   汇总分
-----------------------
1 1.5 2.1
1 1.8 2.1
1 0.8 2.1
1 -2 2.1
2 -5.5 5
2 8.2 5
2 2.3 5
3 0 0
4 3 3
5 0 0

分享到: 更多


------解决方案--------------------
问题是你数据集里都没uid=3和uid=5的纪录。参考
select t.*,round(s.scroe,1) as scroe , round(if(s.total is null,0,s.total),1) as summary from 
(select 1 as uid
union
select 2 as uid
union
select 3 as uid
union
select 4 as uid
union
select 5 as uid) t left join
(select uid,scroe,(select sum(scroe) from a where uid=aa.uid group by uid) as total from a as aa) s
on s.uid = t.uid

------解决方案--------------------

用户表tu

得分表t

SQL:SELECT tu.uid,t.score,a.total from test t right join test_user tu on tu.uid=t.uid left join (SELECT uid,sum(score) as total from test group by uid) a on a.uid=t.uid order by tu.uid

结果

人气教程排行