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.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Combining two queries

Author  Topic 

andypgill
Starting Member

34 Posts

Posted - 2013-08-28 : 17:09:11
Hi

I have two queries in SQL linked to excel.

Report 1 shows

Contract A E N P

Income 5000 6000 8000 4000
Costs 4000 7000 6000 3000

Report2 shows

Contract A B E

CustomerA 500 200 400
CustomerB 450 100 200


Is it possible to combine them so I get


Contract A B E N P

Income 5000 6000 8000 4000
Costs 4000 7000 6000 3000

CustomerA 500 200 400
CustomerB 450 100 200

Thanks


Sent from my iPad

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-28 : 17:20:58
Can you try using a UNION like shown below:
SELECT contract, A, NULL AS B, E, N, P FROM Report1Table
UNION ALL
SELECT contract, A, B, E, NULL, NULL FROM Report2Table
If you have specific ordering needs that would need to be added in.
Go to Top of Page

andypgill
Starting Member

34 Posts

Posted - 2013-08-29 : 02:48:16
quote:
Originally posted by James K

Can you try using a UNION like shown below:
SELECT contract, A, NULL AS B, E, N, P FROM Report1Table
UNION ALL
SELECT contract, A, B, E, NULL, NULL FROM Report2Table
If you have specific ordering needs that would need to be added in.



Hi

Thanks for the reply, however to do that wouldn't I need to know all the data (of which in reality there is lots)
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-08-29 : 03:16:18
quote:
Originally posted by andypgill

quote:
Originally posted by James K

Can you try using a UNION like shown below:
SELECT contract, A, NULL AS B, E, N, P FROM Report1Table
UNION ALL
SELECT contract, A, B, E, NULL, NULL FROM Report2Table
If you have specific ordering needs that would need to be added in.



Hi

Thanks for the reply, however to do that wouldn't I need to know all the data (of which in reality there is lots)


You need to know only about columns involved not on actual data. also all tables should have equal number of columns with corresponding types equal.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

VeeranjaneyuluAnnapureddy
Posting Yak Master

169 Posts

Posted - 2013-08-29 : 05:13:07
SELECT Contract,A,Null AS 'B',E,N,P FROM ReportTable1
UNION all
SELECT Contract,A,B,E,Null AS 'N',Null AS 'P' FROM ReportTable2

veeranjaneyulu
Go to Top of Page
   

- Advertisement -