我正努力解决基于MySQL查询的特定问题。
我有这样的结果集:
Table: Report
mammal_id mammal_name fruit_name gets | total |
3 rabbit apple 4 | 5 |
3 rabbit carrot 4 | 4 |
3 rabbit cabbage 1 | 3 |
2 squirrel nuts 1 | 3 |
2 squirrel cabbage 2 | 2 |
1 chipmunk nuts 2 | 2 |
1 chipmunk apple 1 | 1 |
And I want to filter like this:
Table: Filtered
mammal_id mammal_name fruit_name has
3 rabbit apple 4
3 rabbit carrot 4
3 rabbit cabbage 1
2 squirrel nuts 1
2 squirrel cabbage 2
1 chipmunk nuts 2
1 chipmunk apple 1
洞点是要得到每个哺乳动物携带的水果总量。
现在我有:
SELECT a.mammal_id, b.mammal_id, a.mammal_name, b.mammal_name, a.fruit_name, b.fruit_name, (b.total - a.total) as has
FROM (SELECT * FROM Report (result set)) as a
INNER JOIN (SELECT * FROM Report (result set)) as b
ON a.fruit_name=b.fruit_name WHERE a.mammal_id = b.mammal_id-1
经过这个查询,我得到这样的结果:
Table: Result
a.mammal_id b.mammal_id a.mammal_name b.mammal_name a.fruit_name b.fruit_name has
2 3 squirrel rabbit cabbage cabbge 1
1 2 chipmunk squirrel nuts nuts 1
感谢你对这个问题的任何指导。
最佳答案
下面的查询应该提供您所需的输出。
SELECT mammal_id, mammal_name, fruit_name, SUM(gets) as has
FROM Report GROUP BY mammal_name, fruit_name
关于mysql - 获取每种哺乳动物所关心的水果总量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18347375/