views:

63

answers:

2

I have this data:

name    qty     date                    flag  
---------------------------------------------    
abc     255     11/10/1986 12:00:00 AM  IN
abc     300     11/10/2010 12:00:00 AM  IN
abc     12      11/10/2012 12:00:00 AM  OUT
abc     13      11/9/2010 12:00:00 AM   OUT
NULL    NULL    NULL                    NULL

I want to get sum of qty at that specific row:

  • If flag is "in", then it will add to the sum
  • if flag is "out", then it will subtract from the sum
+13  A: 
SELECT SUM(case flag when 'IN' then qty else -qty end)
from table
WHERE ..... Your conditions here ...
Michael Pakhantsov
A: 

I can think of three ways to do this. The first is a loop with an if statement, I probably wouldn't use that option.

The second is to use Linq to do the calculation, check out this website if you don't know Linq http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

You could probably use Lamda Expressions however I'm not great with them and I'm not 100% sure how to go about it, but I feel Lamda Expressions will most likely give you the most elegant solution.

TheLukeMcCarthy
Is this an answer to a different question? If not then -1 for the suggesting of bringing all the data back to the application and using Linq to aggregate it when a perfectly satisfactory SQL solution exists.
Martin Smith
Thanks Guys Solution Worked Thank You Very much
Rohan
Martin, I assumed that a where clause would be used in the Linq used in the Linq statement, which would only return the required records as Linq creates pretty good SQL statements. Having said that I was looking through the C# tag and missed that this question was actually a sql question
TheLukeMcCarthy
@TheLuke - Remember to add @ before a persons name in a comment so that they are notified of your reply.
Kyle Rozendo
@kyle-rozendo thanks for that, I'm still pretty new to stack overflow, so I'm still finding my way around.
TheLukeMcCarthy