使用GROUP BY内联的SUM列

时间:2018-09-20 17:19:55

标签: sql ms-access

我在Access中有下一张表:

ID  |   Name  |  Dog    |   Cat   |
===================================
1   | A       |   100   |   0     |
1   | B       |   0     |   100   |
1   | C       |   50    |   0     |
2   | A       |   100   |   0     |
2   | B       |   3     |   100   |
2   | C       |   3     |   50    |

通过查询,我需要这样显示它:

ID  |   Name  |  Dog    |   Cat   |
===================================
1   | A       |   100   |   0     |
1   | B       |   0     |   100   |
1   | C       |   50    |   0     |
1   | TOTAL   |   50    |   0     |
2   | A       |   100   |   0     |
2   | B       |   0     |   100   |
2   | C       |   0     |   50    |
2   | TOTAL   |   0     |   -50   |

如您所见,首先我将“狗”和“猫”列求和,然后对“狗-猫”求和,如果该值为正,则转到“狗”列,如果该值为负,则转到“猫”列。我是新来的,我已经检查过类似的问题,但是我想看看解决这个问题的最简单方法。谢谢!

到目前为止,我有

SELECT ID, Name, Dog, Cat
FROM Table
UNION 
SELECT ID, 'Total', SUM(Dog), SUM(Cat)
FROM Table
GROUP BY ID

我知道了:

ID  |   Name  |  Sum(Dog)|   Sum(Cat)|
======================================
1   | A       |   100    |   0       |
1   | B       |   0      |   100     |
1   | C       |   50     |   0       |
1   | TOTAL   |   150    |   100     |
2   | A       |   100    |   0       |
2   | B       |   0      |   100     |
2   | C       |   0      |   50      |
2   | TOTAL   |   100    |   150     |

1 个答案:

答案 0 :(得分:1)

您将使用union allorder by。在MS Access中,我认为是这样:

SELECT ID, Name, SUM(Dog), Sum(Cat)
FROM Table
GROUP BY ID, Name
UNION ALL
SELECT ID, "Total", SUM(Dog), Sum(Cat)
FROM Table
GROUP BY ID
ORDER BY IIF(Name = "Total", 1, 0), Name

您可以尝试使用子查询:

SELECT name, name, num_dogs, num_cats
FROM (SELECT ID, Name, SUM(Dog) as num_dogs, Sum(Cat) as num_cats, 1 as ord
      FROM Table
      GROUP BY ID, Name
      UNION ALL
      SELECT ID, "Total", SUM(Dog), Sum(Cat), 0 as ord
      FROM Table
      GROUP BY ID
     ) as t
ORDER BY ord, Name