Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Sum two fields on different rows in same table to display as third row in result

$
0
0

Hi All,

I'm running version SQL Server 2008R2. I'm trying to add together two items from the same field but from different rows based on the another fields content  while at the same time keeping all other rows in the output result.  My test sample looks like this:

proj | Job | elem | qty |

3570 000  1         400

3570 000  2         300

3570 000  3         0

3570 001  1         500

3570 001  6         100

3570 002  9         900

What I need the output to look like is:

proj | Job | elem | qty | Sum(1&2)|

3570 000  1         400    700

3570 000  2         300    700

3570 000  3         0        NULL or 0

3570 001  1         500     500

3570 001  6         100     NULL or 0

3570 002  9         900     NULL or 0

My attempt at this was to use a join Similar to:

Select a.proj, a.job, a.qty, sum(a.qty)

from TBL1 a OUTER JOIN TBL1 b

ON a.proj = b.proj AND a.job = b.job AND b.elem IN ('1','2')

GROUP BY a.proj,a.job,a.elem

This of course isn't happening any assistance pointing me in the right direction is appreciated.


Sawyer


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>