总和负数和正数

时间:2013-02-19 07:10:47

标签: sql sql-server sql-server-2008 tsql sum

我正在使用SQL Server 2008.我已经为客户进行了销售,我希望将其与前一年客户购买的产品进行比较,并计算增长。一切正常,但一旦客户在其中一个月内出现负数,它就会为Target&增长。

Customer     SalesLastYearMonth      SalesThisYearMonth      Target     Growth
------------------------------------------------------------------------------
abcd         -1                      15                      ????       ???

代码:

SELECT
    Customer,
    CASE 
        WHEN SalesThisYearMonth IS NULL THEN (SalesLastYearMonth * -1)
        WHEN SalesLastYearMonth IS NULL THEN SalesThisYearMonth 
        ELSE SalesThisYearMonth -  SalesLastYearMonth END as Target,
    CASE 
        WHEN SalesThisYearMonth IS NULL THEN -1 
        WHEN SalesLastYearMonth IS NULL THEN 1 
        WHEN SalesThisYearMonth = 0 then -1
        WHEN SalesLastYearMonth = 0 then 1
        ELSE ( SalesThisYearMonth - SalesLastYearMonth) / SalesLastYearMonth END AS Growth

3 个答案:

答案 0 :(得分:0)

假设您想要TARGET = 16,GROWTH = 16,那么应该这样做:

SELECT
    Customer,
    CASE 
        WHEN SalesThisYearMonth IS NULL THEN (SalesLastYearMonth * -1)
        WHEN SalesLastYearMonth IS NULL THEN SalesThisYearMonth 
        ELSE SalesThisYearMonth -  SalesLastYearMonth END as Target,
    CASE 
        WHEN SalesThisYearMonth IS NULL THEN -1 
        WHEN SalesLastYearMonth IS NULL THEN 1 
        WHEN SalesThisYearMonth = 0 then -1
        WHEN SalesLastYearMonth = 0 then 1
        ELSE ( SalesThisYearMonth - SalesLastYearMonth) / ABS(SalesLastYearMonth) END AS Growth

但是,我真的不确定那里的成长 - 不确定为什么要除以SalesLastYearMonth。在上面的情况下这是有效的,但如果SalesLastYearMonth为-4,除以4你想要的是什么?

答案 1 :(得分:0)

您要除以负数:

SalesLastYearMonth = -1

您需要检查它或返回绝对值。

答案 2 :(得分:0)

只是一个小小的建议。尝试使用ISNULL()函数。如果您选择的值为NULL,则可以给出默认返回值。据我所知,它比CASE WHEN快得多。