Mysql 如何在同一SQL语句中使用两个条件对字段求和两次
我有以下SQL语句:Mysql 如何在同一SQL语句中使用两个条件对字段求和两次,mysql,sql,Mysql,Sql,我有以下SQL语句: Select SUM (amount) from accounts Where acctype = 0; 及 我想在一条SQL语句中找出两种情况下的金额之差。这称为条件聚合: SELECT SUM(case when acctype = 0 then amount else 0 end) AS sum0, SUM(case when acctype = 1 then amount else 0 end) AS sum1, SUM(case when accty
Select SUM (amount) from accounts Where acctype = 0;
及
我想在一条SQL语句中找出两种情况下的金额之差。这称为条件聚合:
SELECT
SUM(case when acctype = 0 then amount else 0 end) AS sum0,
SUM(case when acctype = 1 then amount else 0 end) AS sum1,
SUM(case when acctype = 0 then amount else 0 end) -
SUM(case when acctype = 1 then amount else 0 end) AS diff
FROM accounts;
select sum(case when acctype = 0 then amount
when acctype = 1 then - amount
end) as diff
from accounts;
这称为条件聚合:
SELECT
SUM(case when acctype = 0 then amount else 0 end) AS sum0,
SUM(case when acctype = 1 then amount else 0 end) AS sum1,
SUM(case when acctype = 0 then amount else 0 end) -
SUM(case when acctype = 1 then amount else 0 end) AS diff
FROM accounts;
select sum(case when acctype = 0 then amount
when acctype = 1 then - amount
end) as diff
from accounts;
您可以使用条件聚合:
SELECT
SUM(case when acctype = 0 then amount else 0 end) AS sum0,
SUM(case when acctype = 1 then amount else 0 end) AS sum1,
SUM(case when acctype = 0 then amount else 0 end) -
SUM(case when acctype = 1 then amount else 0 end) AS diff
FROM accounts;
select sum(case when acctype = 0 then amount
when acctype = 1 then - amount
end) as diff
from accounts;
您可以使用条件聚合:
SELECT
SUM(case when acctype = 0 then amount else 0 end) AS sum0,
SUM(case when acctype = 1 then amount else 0 end) AS sum1,
SUM(case when acctype = 0 then amount else 0 end) -
SUM(case when acctype = 1 then amount else 0 end) AS diff
FROM accounts;
select sum(case when acctype = 0 then amount
when acctype = 1 then - amount
end) as diff
from accounts;
如果您喜欢“hacks”:
从acctype输入(0,1)的帐户中选择SUM(金额*符号(acctype-0.5))代码>如果您喜欢“hacks”:从acctype输入(0,1)的帐户中选择SUM(金额*符号(acctype-0.5))代码>我们是否可以使用-WHERE acctype之类的值介于0和1之间;。询问我的知识。@Belle:是的,你可以使用一个附加的WHERE
子句,它甚至可以更快地得到结果。我更愿意使用<代码>,其中AccType在(0, 1)中,不过,我认为这更清楚(我们只对值0和1感兴趣,两者之间没有任何值)。谢谢。我们可以使用-WHERE acctype之类的值,介于0和1之间;。询问我的知识。@Belle:是的,你可以使用一个附加的WHERE
子句,它甚至可以更快地得到结果。我更愿意使用<代码>,其中AccType在(0, 1)中,不过,我认为这更清楚(我们只对值0和1感兴趣,两者之间没有任何值)。谢谢你,尽管是我说的,但我认为你在这方面缺少了一个结尾case@GordonLinoff你的回答是正确的,正如RiggsFolly所说的,我们必须在diff之前结束,无论如何,非常感谢你,请把“结束”放在后面制定代码correct@Hamada:此解决方案可能比计算两个不同的sum()
s并将其相减更有效。这与我无关,但我认为您在这方面缺少了一个end
case@Gordon林诺夫:你的回答是正确的,正如里格斯福利所说的,我们必须在不同的情况下先结束,无论如何,非常感谢你,请把“结束”的代码correct@Hamada:此解决方案可能比计算两个不同的sum()
s并将其相减更有效。