在Mysql中的一个查询中获取sum()结果

时间:2010-05-31 01:59:28

标签: sql mysql

我有一张桌子

id name state num
1  x    in    10
2  x    out   1
3  x    in    5
4  x    out   2
5  y    ...
6  y    ...

预期的结果是在一个查询中对“in”和“out”的num求和,然后计算差异,如

name numin numout diff
x    15    3      12
y    ....

由于

1 个答案:

答案 0 :(得分:1)

您想要的是GROUP BY(以及CASE声明):

SELECT
  name,
  SUM(CASE WHEN state='in' THEN num ELSE 0 END CASE) AS numin,
  SUM(CASE WHEN state='out' THEN num ELSE 0 END CASE) AS numout,
  SUM(CASE WHEN state='in' THEN num ELSE -1*num END CASE) AS diff
FROM
  table
GROUP BY
  name