我在sql方面不是很有经验,但通常可以通过构造基本查询,但这对我来说太复杂了。
我有两个查询,每个查询分别给出我需要的结果,但是我需要将它们组合起来以获得我需要的最终结果。
在一个查询中,它会抓取特定学生的所有“分数”并返回平均值。在另一个查询中,我从表中删除了最高和最低记录。
我希望将这些查询组合起来先剥离最高和最低分数,然后仅从剩余记录中返回平均分数。请帮助指导我使用正确的语法。
我的疑问:
这将返回所有最高和最低分数:
SELECT *
FROM `scores`
WHERE `tot_score` = (
SELECT MAX( `tot_score` )
FROM `scores` )
OR `tot_score` = (
SELECT MIN( `tot_score` )
FROM `scores` )
返回平均分数:
SELECT `pres_id`, COUNT( `pres_id` ) , ROUND( AVG( `tot_score` ) , 2 ) , `username`, `name`, `pres_day`
FROM `scores`, `users`
WHERE `users.id_user` = `scores.pres_id`
GROUP BY `pres_id`
如何将这些结合起来以获得我需要的结果?
答案 0 :(得分:5)
我建议你在一个子查询中计算最小值和最大值。然后,您可以使用where
子句简单地获取所需的行来过滤:
SELECT s.`pres_id`, COUNT( `pres_id` ), ROUND( AVG( `tot_score` ) , 2 ) ,
`username`, `name`, `pres_day`
FROM `scores` s join
`users` u
on u.id_user = s.pres_id join
(select s.pres_id, max(tot_score) as maxts, min(tot_score) as mints
from scores s
group by s.pres_id
) ssum
on u.id_user = ssum.pres_id
where s.tot_score > ssum.mints and s.tot_score < ssum.maxts
GROUP BY s.`pres_id`;
我猜你要剥离每个学生的最高分和最低分。如果您只想省略所有学生的最高和最低,请使用以下内容:
SELECT s.`pres_id`, COUNT( `pres_id` ), ROUND( AVG( `tot_score` ) , 2 ) ,
`username`, `name`, `pres_day`
FROM `scores` s join
`users` u
on u.id_user = s.pres_id cross join
(select max(tot_score) as maxts, min(tot_score) as mints
from scores s
) ssum
where s.tot_score > ssum.mints and s.tot_score < ssum.maxts
GROUP BY s.`pres_id`;
编辑:
当学生只有一个分数时保持分数的修改:
SELECT s.`pres_id`, COUNT( `pres_id` ), ROUND( AVG( `tot_score` ) , 2 ) ,
`username`, `name`, `pres_day`
FROM `scores` s join
`users` u
on u.id_user = s.pres_id join
(select s.pres_id, max(tot_score) as maxts, min(tot_score) as mints,
count(*) as cnt
from scores s
group by s.pres_id
) ssum
on u.id_user = ssum.pres_id
where (s.tot_score > ssum.mints and s.tot_score < ssum.maxts) or (cnt = 1)
GROUP BY s.`pres_id`;
答案 1 :(得分:3)
您应该能够反转高/低分数查询,然后将其用作现有平均查询中的结果集:
SELECT `pres_id`, COUNT( `pres_id` ) , ROUND( AVG( `tot_score` ) , 2 ) , `username`, `name`, `pres_day`
FROM (
SELECT `tot_score`
FROM `scores`
WHERE `tot_score` <> (
SELECT MAX( `tot_score` )
FROM `scores` )
OR `tot_score` <> (
SELECT MIN( `tot_score` )
FROM `scores` )
) AS `scores`, `users`
WHERE `users.id_user` = `scores.pres_id`
GROUP BY `pres_id`