组合查询

时间:2018-07-03 16:07:13

标签: mysql sql

MYSQL的新手,但是如何结合这两个查询以显示类型='i'的SUM(总计)减去类型='p'的SUM(总计)。

SELECT userid, SUM(total)
FROM invoices
WHERE type = 'i'
GROUP BY 1

SELECT userid, SUM(total)
FROM invoices
WHERE type = 'p'
GROUP BY 1

1 个答案:

答案 0 :(得分:3)

您可以使用case表达式

SELECT userid, 
    SUM(case when type = 'i' then total else 0 end) typei,
    SUM(case when type = 'p' then total else 0 end) typep,
    SUM(case when type = 'i' then total else 0 end) - SUM(case when type = 'p' then total else 0 end) as diff
FROM invoices
GROUP BY userid

或者您可以将其写为

SUM(case when type = 'i' then total when type = 'p' then -1 * total else 0 end) as diff

编辑:要过滤聚合产生的结果,可以使用having子句

SELECT userid, 
    SUM(case when type = 'i' then total else 0 end) typei,
    SUM(case when type = 'p' then total else 0 end) typep,
    SUM(case when type = 'i' then total else 0 end) - SUM(case when type = 'p' then total else 0 end) as diff
FROM invoices
GROUP BY userid
HAVING diff > 0