Groups | Blog | Home
all groups > sql server clients > march 2006 >

sql server clients : Writing a Query to Subtract 2 subqueries


Mike9900
3/31/2006 1:51:03 AM
I need to subtract two types of subtotal, SUM(Subtotal); if the type=1 or
type=2. For example, (Sum(Subtotal) if type=1) - ( Sum(Subtotal) if type2=2)

I need to do this in a single query if possible, please.

Table Schemas: There are 3 columns ID, Subtotal, Type:

ID Subtotal Type

1 900 1
2 321 2
3 434 1
4 1234 1
5 4324 2


--
Tom Cooper
3/31/2006 1:53:52 PM
Select Type,
Sum(Case When Type = 1 Then Subtotal Else 0 End) As 'Type 1 Subtotal',
Sum(Case When Type = 2 Then Subtotal Else 0 End) As 'Type 2 Subtotal'
From MyTable
Group By Type
Order By Type

Tom

[quoted text, click to view]

Tom Cooper
3/31/2006 1:58:58 PM
Sorry, misread your question, you want:

Select
Sum(Case When Type = 1 Then Subtotal
When Type = 2 Then -Subtotal Else 0 End) As 'Difference'
From MyTable

Tom

[quoted text, click to view]

Mike9900
3/31/2006 11:32:02 PM
Thanks, it worked! :)
--
Mike


[quoted text, click to view]
AddThis Social Bookmark Button