Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 *SOLVED* Variance of 2 summed values

Author  Topic 

davidais
Starting Member

17 Posts

Posted - 2012-10-04 : 10:54:58
Hi all,

How would I display in a new column the difference of [Value2012] - [Value2011] and exclude any instances where [Value2012] - [Value2011] = 0

SELECT
tbCustomers.AccountNumber, tbCustomers.CustomerName,
SUM(CASE WHEN InvoiceDate BETWEEN '2011-01-01' AND '2011-07-31' THEN InvoiceValue ELSE 0 END) AS Value2011,
SUM(CASE WHEN InvoiceDate BETWEEN '2012-01-01' AND '2012-07-31' THEN InvoiceValue ELSE 0 END) AS Value2012

FROM
tbSalesHistory
JOIN tbCustomers ON tbSalesHistory.AccountNumber = tbCustomers.AccountNumber

GROUP BY
tbCustomers.AccountNumber, tbCustomers.CustomerName

Many thanks, D

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-10-04 : 11:05:26
[code]
SELECT
tbCustomers.AccountNumber, tbCustomers.CustomerName,
SUM(CASE WHEN InvoiceDate BETWEEN '2011-01-01' AND '2011-07-31' THEN -1 * InvoiceValue
WHEN InvoiceDate BETWEEN '2012-01-01' AND '2012-07-31' THEN InvoiceValue ELSE 0 END) AS [Value2012-Value2011]

FROM
tbSalesHistory
JOIN tbCustomers ON tbSalesHistory.AccountNumber = tbCustomers.AccountNumber

GROUP BY
tbCustomers.AccountNumber, tbCustomers.CustomerName
HAVING SUM(CASE WHEN InvoiceDate BETWEEN '2011-01-01' AND '2011-07-31' THEN -1 * InvoiceValue
WHEN InvoiceDate BETWEEN '2012-01-01' AND '2012-07-31' THEN InvoiceValue ELSE 0 END)>0
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

davidais
Starting Member

17 Posts

Posted - 2012-10-04 : 11:14:07
Awesome
Go to Top of Page

davidais
Starting Member

17 Posts

Posted - 2012-10-04 : 11:35:13
out of curiosity what does the [ -1 * ] part of the expression do?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-10-04 : 11:53:00
quote:
Originally posted by davidais

out of curiosity what does the [ -1 * ] part of the expression do?


it negates the values for last year inside SUM to give variance from current year ie 2012

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -