Alan.B (9/12/2013)
Sean Lange (9/12/2013)
select SUM(Case when MyType = 2 then -1 * MyHours else MyHours end) as TotalHours
from #SomeTable
If I understand the original OP correctly (" If something has been credited, the billed item row should be excluded") this would not provide the right answer with this sample data:
INSERT INTO #SomeTable
SELECT 'xxx',3,1 UNION ALL
SELECT 'yyy',3,2 UNION ALL
SELECT 'xxx',4,1 UNION ALL
SELECT 'xxx',1,1;
I believe the right answer would be 8, your query would return a 5.
... but who knows without any ddl :Whistling:
The OP stated that the query should return 5.
and I do a sum of the hours, I get 11. However, a Type of 1 is a billed item and 2 is a credit item. If something has been credited, the billed item row should be excluded, resulting in a total of 5.
To be fair, the way I wrote that makes the most sense because you could have a credit that is not for the full amount. Imagine if there was 3 hours billed but only 2 credited.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/