Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Mikehjun
Starting Member
24 Posts |
Posted - 2013-03-11 : 18:18:49
|
I have Material, Labor, Equipment tables. Each table has field for AccountNum, WorkorderID, Units, Cost.I need to sum total cost of all three based on AccountNum.each table looks like,Material..WO, Acct, Unit, Cost1, 101, 1, 251, 101, 2, 201, 103, 1, 151, 103, 1, 10Equipment and Labor also are similar.SELECTE.ACCTNUM, SUM(COST)FROM [CLGT].[azteca].[EQUIPMENTCOSTACT] EWHERE E.WORKORDERID = 98GROUP BY E.ACCTNUMUNIONSELECTL.ACCTNUM, SUM(COST)FROM [CLGT].[azteca].LABORCOSTACT LWHERE L.WORKORDERID = 98GROUP BY L.ACCTNUMUNIONSELECTM.ACCTNUM, SUM(COST)FROM [CLGT].[azteca].MATERIALCOSTACT MWHERE M.WORKORDERID = 98GROUP BY M.ACCTNUMAfter I run this, I got the result like,ACCTNum COST101-85-0732 0.00101-85-0733 13.32101-85-0733 98.00101-85-0733 697.18111-85-0811 162.26I'd like to have the final table looks like,101-85-0732 0.00101-85-0733 808.50111-85-0811 162.26 |
|
LoztInSpace
Aged Yak Warrior
940 Posts |
Posted - 2013-03-11 : 21:00:04
|
selectacctnum, sum(cost)from(SELECTE.ACCTNUM, COSTFROM [CLGT].[azteca].[EQUIPMENTCOSTACT] EWHERE E.WORKORDERID = 98UNION allSELECTL.ACCTNUM, COSTFROM [CLGT].[azteca].LABORCOSTACT LWHERE L.WORKORDERID = 98UNION allSELECTM.ACCTNUM, COSTFROM [CLGT].[azteca].MATERIALCOSTACT MWHERE M.WORKORDERID = 98) xgroup by ACCTNUMNote use of UNION ALL.If you use just UNION you will drop out identical rows. |
|
|
|
|
|
|
|