Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL Query

Status
Not open for further replies.

zsfhaergta

Programmer
Oct 6, 2008
26
0
0
US
Hi, I'm not quite a sql expert, and have been having some trouble figuring this out:

I have one table with ID, Side=1 or 2, and Qty. I'd like to group by ID where sum(Qty) where Side=1 - sum(Qty) where Side=2.

So basically the difference of all Qty's having side=1 minus all Qty's having side=2.

Table:
+--------+------+------+
| ID | Side | Qty |
+--------+------+------+
| 217938 | 1 | 100 |
| 217938 | 1 | 300 |
| 217938 | 1 | 250 |
| 217938 | 2 | 275 |
| 217938 | 2 | 120 |
| 217938 | 2 | 30 |
| 217939 | 2 | 125 |
+--------+------+------+


Result:

ID Difference
217938 225
217939 -125

Anyone able to figure this out? Thanks
 
Hope it helps.

Code:
SELECT A.ID, COALESCE(B.Qty, 0)-A.Qty FROM 
	(SELECT ID, SUM(Qty) AS Qty, AVG(Side) AS Side FROM #T WHERE Side = 2 GROUP BY ID, Side) AS A
		LEFT OUTER JOIN 
	(SELECT ID, SUM(Qty) AS Qty, AVG(Side) AS Side FROM #T WHERE Side = 1 GROUP BY ID, Side) AS B
		ON A.ID = B.ID
 
Forgot to mention, replace #T with your table.

:)
 
Hi,

Code:
select distinct(id),
isnull((select sum(qty) from [Table] t1 where t1.id = t.id and side = 1),0) - 
isnull((select sum(qty) from [Table] t1 where t1.id = t.id and side = 2),0) as calc
from [Table] t

Ryan
 
select ID, Sum1 - Sum2 as difference from (select ID, sum(case when Side=1 then qty else 0 end) as Sum1, sum(case when Side=2 then qty else 0 end) as Sum2 from myTable group by ID) mySums
 
select ID,sum(qty * case when side = 1 then 1 else -1 end) as TotalQty
From YourTable
Group by ID

If you could change 2 with -1 in the table, you can get rid of Case and only have sum(qty * side)
This could have the advantage of being able to cancel any entry by setting its 'side' to 0.

HTH

[pipe]
Daniel Vlas
Systems Consultant

 
Hi Danvlas,

Yes, this is nice. I was only half way through with my idea and you made it much simplier.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top