嗨,我很难理解如何从数据库中获取MAX()和SUM()
我的数据库有3个colums id - stuff - 得分看起来像这样
ID-STUF得分
1-1-2
1-1-3
1-2-1
1-2-3
1-3-1
1-3-3
我需要做一个
MAX(得分),其中stuff = 1且id = 1
MAX(得分),其中stuff = 2且id = 1
MAX(得分),其中stuff = 3且id = 1
等
然后a SUM(得分)全部为MAX(得分)
我有数百行,我想不出一种让它发生的方法
答案 0 :(得分:2)
为每个你需要的东西制作子查询表导数,然后将它们全部加在一起。
SELECT SUM(a.max+b.max+c.max) as total
FROM (
(
SELECT MAX(score) as max
FROM tablename
WHERE stuff = 1 AND id = 1
) as a,
(
SELECT MAX(score) as max
FROM tablename
WHERE stuff = 2 AND id = 1
) as b,
(
SELECT MAX(score) as max
FROM tablename
WHERE stuff = 3 AND id = 1
) as c
);
输出:
_____________
| total |
+-----------+
| 12345 |
+-----------+
答案 1 :(得分:1)
尝试使用group by
获取最高分数,然后对结果求和。
表中的记录
我添加了更多记录,因此max(score)
对于每个stuf
都不一样。
mysql> select * from stuff;
+------+------+-------+
| id | stuf | score |
+------+------+-------+
| 1 | 1 | 2 |
| 1 | 1 | 3 |
| 1 | 2 | 1 |
| 1 | 2 | 3 |
| 1 | 3 | 1 |
| 1 | 3 | 3 |
| 1 | 3 | 4 |
| 1 | 3 | 1 |
| 1 | 2 | 5 |
| 1 | 2 | 1 |
+------+------+-------+
10 rows in set (0.00 sec)
分组
mysql> select id, max(score) as max_score from stuff group by stuf;
+------+-----------+
| id | max_score |
+------+-----------+
| 1 | 3 |
| 1 | 5 |
| 1 | 4 |
+------+-----------+
3 rows in set (0.00 sec)
总结
mysql> select sum(max_score) from (select id, max(score) as max_score
from stuff group by stuf) sum_me;
+----------------+
| sum(max_score) |
+----------------+
| 12 |
+----------------+
1 row in set (0.00 sec)
一个注意事项
请注意,如果您有更多ID,则需要将查询限制为您感兴趣的ID或适当地对最后一个查询进行分组。
mysql> select id, sum(max_score) from (select id, max(score) as max_score
from stuff group by id, stuf) sum_me group by id;
答案 2 :(得分:1)
你可以试试这个
SELECT SUM(a.max) as total
FROM (
(
SELECT MAX(score) as max
FROM tablename
GROUP BY stuf, id
) as a
);