开发者

Get sum() result in one query in Mysql

开发者 https://www.devze.com 2023-01-01 20:23 出处:网络
I have a table id name state num 1xin10 2xout1 3xin5 4xout2 5y... 6y... The expected result is to sum the num for \'in\' and \'out开发者_StackOverflow社区\' in one query and then calculate the diff

I have a table

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

The expected result is to sum the num for 'in' and 'out开发者_StackOverflow社区' in one query and then calculate the difference, like

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

Thanks


What you want is GROUP BY (and the CASE statement):

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
0

精彩评论

暂无评论...
验证码 换一张
取 消