我试图将以下每个总和作为字段,我只获得外部的一个,其他两个返回未定义的索引。
如何将它们作为字段放在外面?
SELECT
(SELECT SUM(amount) AS income
FROM transaction
WHERE
type = '1' && state = 'a')
- (SELECT SUM(amount) AS expense
FROM transaction
WHERE
type = '2' && state = 'a')
AS balance
余额有效,但对于收入和支出,我得到了未定义的索引。
答案 0 :(得分:1)
您可以使用case
和sum
来获取每个结果:
select sum(case when `type` = '1' then `amount` else 0 end) as `income`
, sum(case when `type` = '2' then `amount` else 0 end) as `expense `
, sum((case when `type` = '2' then -1 else 1 end) * `amount`) as `difference`
from `transaction`
where `type` in ('1', '2')
where `state` = 'a'
答案 1 :(得分:1)
使用条件聚合:
SELECT SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0
END) as income,
SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0
END) as balance
FROM transaction;
如果你仍然想要差异,那么你需要重复逻辑:
SELECT SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0
END) as income,
SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0
END) as expense,
(SUM(CASE WHEN type = '1' AND state = 'a' THEN amount ELSE 0 END) -
SUM(CASE WHEN type = '2' AND state = 'a' THEN amount ELSE 0 END)
) as balance
FROM transaction;
编辑:
实际上,最好将常见条件分解为WHERE
子句:
SELECT SUM(CASE WHEN type = '1' THEN amount ELSE 0 END) as income,
SUM(CASE WHEN type = '2' THEN amount ELSE 0 END) as expense,
(SUM(CASE WHEN type = '1' THEN amount ELSE 0 END) -
SUM(CASE WHEN type = '2' THEN amount ELSE 0 END)
) as balance
FROM transaction
WHERE state = 'a' AND type IN ('1', '2');
这可以利用transaction(state, type, amount)
上的索引。
答案 2 :(得分:1)
您无法访问income
和expense
,因为它们仅在各自的子查询中定义,而不是在顶级查询中定义,后者只有一个字段 - 它们之间的差异。我放入一个子查询,然后选择它们和它们之间的区别。为了简化此查询并删除对子查询的需求,您可以通过向where
中的case
表达式提取不同的条件来模拟两个不同sum
子句的行为参数:
SELECT income, expense, income - expense AS balance
FROM (SELECT SUM(CASE type WHEN 1 THEN amount ELSE NULL) AS income,
SUM(CASE type WHEN 2 THEN amount ELSE NULL) AS expense,
FROM `transaction`
WHERE state = 'a') t