MySQL希望从两个SQL语句中使用SUM和Minus

时间:2015-12-11 19:45:44

标签: mysql

我想要SUM第一个Statement(A)和Second Statement(B)然后我想得到A-B的结果。之后我得到输出GROUP BY who

SELECT `who`, mpoints-spoints AS netpoints 
FROM
(
SELECT `who`,`points`, SUM(points) AS mpoints FROM `game` WHERE (`datetime` BETWEEN '2015-12-1' AND '2015-12-31') AND (`cal`='1') AND (`result`='1' OR `result`='2') GROUP BY `who`
) t1,
(
SELECT `who`,`points`, SUM(points) AS spoints FROM `game` WHERE (`datetime` BETWEEN '2015-12-1' AND '2015-12-31') AND (`cal`='1') AND (`result`='3' OR `result`='4') GROUP BY `who`
) t2
ORDER BY netpoints DESC
GROUP BY `who`

我希望输出像

whlie($rs=mysql_fetch_assoc($query)){
No.    Who.           Points
$i++   $rs['who']        $rs['netpoints']
}

1 个答案:

答案 0 :(得分:0)

查询可能如下所示,但我还没有测试过。

SELECT `who`, mpoints-spoints AS netpoints 
FROM
(
SELECT `who`,`points`, SUM(points) AS mpoints, 0 as spoints FROM `game` WHERE (`datetime` BETWEEN '2015-12-1' AND '2015-12-31') AND (`cal`='1') AND (`result`='1' OR `result`='2') GROUP BY `who`
UNION ALL
SELECT `who`,`points`, 0 as mpoints, SUM(points) AS spoints FROM `game` WHERE (`datetime` BETWEEN '2015-12-1' AND '2015-12-31') AND (`cal`='1') AND (`result`='3' OR `result`='4') GROUP BY `who`
) A
GROUP BY `who`
ORDER BY netpoints;
相关问题