获得每个哺乳动物关心的水果总量

时间:2013-08-21 01:12:46

标签: mysql sql stored-procedures

我正在努力解决基于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

感谢有关此问题的任何指导。

2 个答案:

答案 0 :(得分:1)

以下查询应该可以为您提供所需的输出。

SELECT mammal_id, mammal_name, fruit_name, SUM(gets) as has
FROM Report GROUP BY mammal_name, fruit_name

答案 1 :(得分:0)

要获取每只动物在“获取”列中的项目总数,您需要

SELECT mammal_id, mammal_name, SUM(gets)
FROM Report 
GROUP BY mammal_id, mammal_name

如果那不是您要求的,请澄清问题。