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)
 Ceat table based on multiple SELECT Statement

Author  Topic 

SQL-NeewBie
Starting Member

2 Posts

Posted - 2014-01-23 : 11:04:07
Hi
I have an SQL problem. I want to  create an new table (if its possible - else im open
for other options) there I can combine the two select statements I have in my script.
NOTE: Both Select querys dont have the exactly same columns or data.
 
Why I use two select statements is bcz I calculate the value in the first select statement.

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2014-01-23 : 11:49:09
I'm not following your question.

Do you want to know how to create a table? Or do you want to combine two queries into one? Or are you trying to create a table from a query (INSERT INTO)? or...?

Here are some links that might help you construct your question in more detail so we can help you better:
http://www.sqlservercentral.com/articles/Best+Practices/61537/
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx
Go to Top of Page

SQL-NeewBie
Starting Member

2 Posts

Posted - 2014-01-23 : 13:18:06
Hi again,

Sorry if I was unclear. I want to combine two select statements - I dont know if its mot easy to create an table to do this or how the most easy way is.

As I wrote earliyer - I dont have same columns/data in both select only 2-3 joins with same data.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-23 : 13:25:41
quote:
Originally posted by SQL-NeewBie

Hi again,

Sorry if I was unclear. I want to combine two select statements - I dont know if its mot easy to create an table to do this or how the most easy way is.

As I wrote earliyer - I dont have same columns/data in both select only 2-3 joins with same data.


so far as select staements have some columns in common you can join between them by using derived table
ie like

SELECT *
FROM (First select) s1
JOIN (second select)s2
ON s2.commoncol1 = s1.commoncol1
AND s2.commoncol2 = s1.commoncol2
...


or if you're looking at horizontally merging them use UNION or UNION ALL. In this case you need to add a placeholder for missing columns
ie say select statement 1 has col1,col2,col3,Col4,Col6
select statement2 has col1,col3,col5,col7
then use like


SELECT Col1,Col2,Col3,Col4,NULL,Col6,NULL
FROM (Select statement1)
UNION ALL
SELECT Col1,NULL,Col3,NULL,Col5,NULL,Col7
FROM (Select statement2)

also if corresponding datatypes are different you need to cast them to similar types before UNION ALL

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

- Advertisement -