来自同一个表的高级SQL SUM列

时间:2012-11-03 03:16:08

标签: sql sum

我有这张桌子......

+-----+--------+------+-----+-----+
|categ| nAME   | quan |IDUNQ|   ID|
+-----+--------+------+-----+-----+
|   1 | Z      |    3 |   1 |  15 |
|   1 | A      |    3 |   2 |  16 |
|   1 | B      |    3 |   3 |  17 |
|   2 | Z      |    2 |   4 |  15 |
|   2 | A      |    2 |   5 |  16 |
|   3 | Z      |    1 |   6 |  15 |
|   3 | B      |    1 |   7 |  17 |
|   2 | Z      |    1 |   8 |  15 |
|   2 | C      |    4 |   8 |  15 |
|   1 | D      |    1 |   8 |  15 |
+-----+--------+------+-----+-----+

我需要获得类别2的类别1 + Z的 Z - 类别3的Z

例如,(3 + 3-1)= 5 ==>猫1的3只,猫2的3只,3只猫的3只

最终结果应该是......

Z ==> 5
A ==> 5
B ==> 2
C ==> 4

2 个答案:

答案 0 :(得分:7)

注意:我假设您的示例中的“C”数据被错误地省略了。

SELECT nAME, SUM(CASE categ WHEN 3 THEN 0-quan ELSE quan END) AS quan
FROM theTable
GROUP BY nAME

SQL Fiddle

答案 1 :(得分:-2)

SELECT name, SUM(quan) AS sum
FROM   tableName
GROUP BY name, categ

这应该有用。