SQL条件加法或减法

时间:2009-09-15 21:40:11

标签: sql

我有一张表,我需要在一个字段上做一些简单的数学运算。我在SQL中尝试嵌套的SELECTS,IF / THEN或CASE语句无济于事
示例表:
wYear,yMonth,Account,Usage,Serv_code
2008,9,12345,1000,Banana
2008,9,12345,5000,Banana
2008,9,12345,4000,Apple
2007,5,54321,1500,Banana


我需要分组依据wYear,yMonth,Account并添加“用法”WHERE Serv_code ='Banana'...

选择wYear,yMonth,Account,SUM(用法)作为“Totals”
来自myTable
在哪里Serv_code ='香蕉'
分组依据,yMonth,账户

但是我碰到了墙 - 如果“Serv_code”确实等于'Apple'(WHERE Serv_code ='Apple'),我需要从SUM(用法)中减去'Apple'用法。

使用上表的示例结果:
2008,9,12345,2000
2007,5,54321,1500

对于SQL来说,我是一个黑客,答案很明显,但那是其中一天。

5 个答案:

答案 0 :(得分:1)

我希望这就是你想要的:

SELECT 
    banana.wYear, 
    banana.yMonth, 
    banana.Account, 
    totals_banana - totals_apple AS totals
FROM
(
    SELECT wYear, yMonth, Account, SUM(Usage) as "totals_banana"
    FROM myTable 
    WHERE Serv_code = 'Banana'
    GROUP BY wYear, yMonth, Account
) banana
INNER JOIN 
(
    SELECT wYear, yMonth, Account, SUM(Usage) as "totals_apple"
    FROM myTable 
    WHERE Serv_code = 'Apple'
    GROUP BY wYear, yMonth, Account
) apple 
ON 
     banana.wYear = apple.wYear 
     AND banana.yMonth = apple.yMonth 
     AND banana.Account = apple.Account

答案 1 :(得分:1)

SELECT wYear, yMonth, Account, SUM(case when Serv_code  = 'Banana' then
Usage when Serv_Code = 'Apple' then -Usage else 0 end) as "Totals"
FROM myTable

GROUP BY wYear, yMonth, Account

测试友好版

Declare @myTable table (wYear int, ymonth int, Account varchar(20), 
Usage int, Serv_Code varchar(20))

Insert into @mytable values (2008, 9, '12345', 1000, 'Banana')
Insert into @mytable values (2008, 9, '12345', 5000, 'Banana')
Insert into @mytable values (2008, 9, '12345', 4000, 'Apple')
Insert into @mytable values (2007, 5, '54321', 1500, 'Banana')

SELECT wYear, yMonth, Account, SUM(case when Serv_code  = 'Banana' then
Usage when Serv_Code = 'Apple' then -Usage else 0 end) as "Totals"
FROM @myTable

GROUP BY wYear, yMonth, Account


wYear   yMonth  Account Totals
2007    5   54321   1500
2008    9   12345   2000

答案 2 :(得分:1)

您可以使用case语句获取正值或负值,具体取决于Serv_code中的值:

select wYear, yMonth, Account, sum(Usage * case Serv_code when 'Apple' then -1 else 1 end) as "Totals"
from myTable
where Serv_code in ('Banana', 'Apple')
group by wYear, yMonth, Account

答案 3 :(得分:0)

我怀疑它的效率,但这应该可以解决问题

SELECT 
    wYear, yMonth, Account, 
    (
      (SELECT SUM(Usage) FROM myTable AS m 
        WHERE m.wYear=wYear AND 
              m.yMonth=yMonth AND 
              m.Account=Account AND 
              m.Serv_code='Banana') -
      (SELECT SUM(Usage) FROM myTable AS m 
        WHERE m.wYear=wYear AND 
              m.yMonth=yMonth AND 
              m.Account=Account AND 
              m.Serv_code='Apple')
   ) as "Totals"
FROM myTable 
GROUP BY wYear, yMonth, Account

答案 4 :(得分:0)

也许这可行 -

SELECT wYear,yMonth,Account, SUM(用例='Apple'然后用法* - 否则用法结束时的情况)为“Totals” 来自myTable WHERE Serv_code ='香蕉' 分组依据,yMonth,账户