我的第一个查询返回一周的平均值:
SELECT POSITION, PLAYER, SUM( POINTS ) / COUNT( DISTINCT YEAR, WEEK ) AS 'avg'
FROM SCHEDULE WHERE WEEK = 1 GROUP BY PLAYER HAVING COUNT( DISTINCT YEAR, WEEK ) >2
ORDER BY avg DESC
我的第二个查询返回整体平均值:
SELECT POSITION, PLAYER, SUM( POINTS ) / COUNT( DISTINCT YEAR, WEEK ) AS 'avg'
FROM SCHEDULE GROUP BY PLAYER HAVING COUNT( DISTINCT YEAR, WEEK ) >2
ORDER BY avg DESC
我希望从查询2中减去查询1并按降序显示结果。
答案 0 :(得分:1)
以下内容如何:
SELECT m.POSITION, m.PLAYER, (m.Overallavg - m.WeeklyAvg) AS NewValue
FROM
(
SELECT s1.POSITION, s1.PLAYER, SUM(s1.POINTS)/COUNT(DISTINCT s1.YEAR, s1.WEEK) AS Overallavg,
(
SELECT SUM(s2.POINTS)/COUNT(DISTINCT s2.YEAR, s2.WEEK)
FROM SCHEDULE s2
WHERE WEEK = 1 AND s2.PLAYER = S1.PLAYER
) AS WeeklyAvg
FROM SCHEDULE s1
GROUP BY s1.PLAYER
HAVING COUNT(DISTINCT s1.YEAR, s1.WEEK) > 2
) m
ORDER BY (Overallavg - WeeklyAvg) DESC
答案 1 :(得分:1)
SELECT
WA.POSITION,
WA.PLAYER,
WA.avg as 'wk_avg',
OA.avg as 'overall_avg',
WA.avg - OA.avg as 'diff'
FROM
(SELECT POSITION, PLAYER, SUM( POINTS ) / COUNT( DISTINCT YEAR, WEEK ) AS 'avg'
FROM SCHEDULE WHERE WEEK = 1 GROUP BY PLAYER HAVING COUNT( DISTINCT YEAR, WEEK ) >2
) WA
INNER JOIN
(SELECT POSITION, PLAYER,SUM( POINTS ) / COUNT( DISTINCT YEAR, WEEK ) AS 'avg'
FROM SCHEDULE GROUP BY PLAYER HAVING COUNT( DISTINCT YEAR, WEEK ) >2
) OA
ON WA.POSITION = OA.POSITION and WA.PLAYER = OA.PLAYER
ORDER BY WA.avg - OA.avg DESC
答案 2 :(得分:0)
except运算符将是一种方式,但mysql不接受它。
我使用NOT IN ...
进行了此查询SELECT
S1.POSITION, S1.PLAYER, SUM( S1.POINTS ) / COUNT( DISTINCT S1.YEAR, S1.WEEK ) AS 'S1AVG'
FROM
SCHEDULE S1 WHERE (S1.POSITION, S1.PLAYER, S1AVG) NOT IN
(
SELECT
S2.POSITION, S2.PLAYER, SUM( S2.POINTS ) / COUNT( DISTINCT S2.YEAR, S2.WEEK ) AS 'S2AVG'
FROM
SCHEDULE S2 WHERE S2.WEEK = 1 GROUP BY S2.PLAYER HAVING COUNT( DISTINCT S2.YEAR, S2.WEEK ) > 2
ORDER BY S2AVG DESC
)
GROUP BY S1.PLAYER
HAVING COUNT( DISTINCT S1.YEAR, S1.WEEK ) > 2
ORDER BY S1AVG DESC
答案 3 :(得分:0)
不确定这是否适用于MySQL
SELECT @result = (QUERY1) - (QUERY2)
或者像这样
SELECT (QUERY1) - (QUERY2)