Solved

SQL Join two SQL Statements to get a new resultset.

Posted on 2011-10-01
8
367 Views
Last Modified: 2012-05-12
Hi,

I have two SQL Queries that I would like to join two SQL statements into one result set.

I have provided the detail below in the code section to make it more readable :)

Thanks,

Ward.
Here is my first SQL statement and results:

advert.sql:
----------

SELECT     v_Advertisement.AdvertisementID, v_Advertisement.AdvertisementName, v_Package.PackageID, v_Package.Name, v_Advertisement.ProgramName, 
                      v_Collection.CollectionID, v_Collection.Name AS [Collection Name], v_Package.PackageType
FROM         v_Advertisement INNER JOIN
                      v_Package ON v_Advertisement.PackageID = v_Package.PackageID INNER JOIN
                      v_Collection ON v_Advertisement.CollectionID = v_Collection.CollectionID
ORDER BY v_Advertisement.AdvertisementID

Results:

AdvertisementID AdvertisementName             PackageID Name                     ProgramName              CollectionID Collection Name   PackageType
--------------- ----------------------------- --------- ------------------------ ------------------------ ------------ ----------------- -----------
L03200A5        Install Comic Life (AD1)      L030018B  Comic Life               [Virtual application]    L030006D     Deployment Test   7
L03200A6        Install Open Office (AD2)     L030018C  OO33                     [Virtual application]    L030006D     Deployment Test   7
L03200A7        Install Virtual Apps TS       L0300190  Install Virtual Apps     *                        L030006D     Deployment Test   4
L03200A8        SD1Advert                     L030018D  Package1                 Program1                 L030006C     LEVEL3_Query      0
L03200A9        SD2Advert                     L030018E  Package2                 Program2                 L030006C     LEVEL3_Query      0
L03200AA        SD3Advert                     L030018F  Package3                 Program3                 L030006C     LEVEL3_Query      0


Here is my second SQL statement and results:

collection.sql:
--------------

select CollectionID, Name as 'Machine' from v_FullCollectionMembership where IsClient = 1 ORDER BY CollectionID, 'Machine'

CollectionID Machine
------------ ------------
L030006C     LEVEL3
L030006D     PC1
L030006D     PC2
L030006D     PC3
L030006D     XP1
L030006D     LEVEL3

(6 row(s) affected)

So I would like to produce a result set that looks like the result set below. Note they are joined on CollectionID.

AdvertisementID AdvertisementName             PackageID Name                     ProgramName              CollectionID Collection Name   PackageType  Machine  Machine Machine Machine Machine Machine
--------------- ----------------------------- --------- ------------------------ ------------------------ ------------ ----------------- -----------  -------  ------- ------- ------- ------- -------
L03200A5        Install Comic Life (AD1)      L030018B  Comic Life               [Virtual application]    L030006D     Deployment Test   7            LEVEL3   PC1     PC2     PC3     XP1     LEVEL3
L03200A6        Install Open Office (AD2)     L030018C  OO33                     [Virtual application]    L030006D     Deployment Test   7            LEVEL3   PC1     PC2     PC3     XP1     LEVEL3
L03200A7        Install Virtual Apps TS       L0300190  Install Virtual Apps     *                        L030006D     Deployment Test   4            LEVEL3   PC1     PC2     PC3     XP1     LEVEL3
L03200A8        SD1Advert                     L030018D  Package1                 Program1                 L030006C     LEVEL3_Query      0            LEVEL3
L03200A9        SD2Advert                     L030018E  Package2                 Program2                 L030006C     LEVEL3_Query      0            LEVEL3
L03200AA        SD3Advert                     L030018F  Package3                 Program3                 L030006C     LEVEL3_Query      0            LEVEL3

Open in new window

0
Comment
Question by:whorsfall
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 29

Expert Comment

by:sammySeltzer
ID: 36898330
You can use UNION query as long as the fieldnames from first query are of the same datatype as the second query.

For instance:

SELECT     v_Advertisement.AdvertisementID, 
           v_Advertisement.AdvertisementName, 
           v_Package.PackageID, 
           v_Package.Name, 
           v_Advertisement.ProgramName, 
           v_Collection.CollectionID, 
           v_Collection.Name AS [Collection Name], 
           v_Package.PackageType
FROM   v_Advertisement INNER JOIN
       v_Package ON v_Advertisement.PackageID = v_Package.PackageID INNER JOIN
       v_Collection ON v_Advertisement.CollectionID = v_Collection.CollectionID
ORDER BY v_Advertisement.AdvertisementID

UNION ALL

SELECT 
         CollectionID, '', '', '', '', '', '', ''
         Name as 'Machine' 
FROM  v_FullCollectionMembership where IsClient = 1 ORDER BY CollectionID, 'Machine'

Open in new window

0
 
LVL 29

Expert Comment

by:sammySeltzer
ID: 36898333
The total number of fieldnames from first query must be the same as those of the second query.

The example I gave above shows that second query has one more fieldname than the first query.

So,

SELECT     v_Advertisement.AdvertisementID, 
           v_Advertisement.AdvertisementName, 
           v_Package.PackageID, 
           v_Package.Name, 
           v_Advertisement.ProgramName, 
           v_Collection.CollectionID, 
           v_Collection.Name AS [Collection Name], 
           v_Package.PackageType
FROM   v_Advertisement INNER JOIN
       v_Package ON v_Advertisement.PackageID = v_Package.PackageID INNER JOIN
       v_Collection ON v_Advertisement.CollectionID = v_Collection.CollectionID
ORDER BY v_Advertisement.AdvertisementID

UNION ALL

SELECT 
         CollectionID, '', '', '', '', '', '',
         Name as 'Machine' 
FROM  v_FullCollectionMembership where IsClient = 1 ORDER BY CollectionID, 'Machine'

Open in new window

0
 

Author Comment

by:whorsfall
ID: 36898343
Hi,

Thanks for that the first statement returns:

Msg 156, Level 15, State 1, Line 14
Incorrect syntax near the keyword 'UNION'.
Msg 156, Level 15, State 1, Line 18
Incorrect syntax near the keyword 'as'.


and the second statement returns:

Msg 156, Level 15, State 1, Line 14
Incorrect syntax near the keyword 'UNION'.

Also is there a way to do it where I don't have to padd the number of fields as you suggest as I was hoping the SQL statement could be able to deal with this.

Thanks,

Ward
0
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 
LVL 60

Expert Comment

by:Kevin Cross
ID: 36898345
It appears you need to do a PIVOT. Is there a finite list of [Machine] values.

If it is, then something like this may be an alternative:
select CollectionID
    , [LEVEL3], [PC1], [PC2], [PC3], [XP1]
from 
(
select CollectionID, Name as [Machine] 
from v_FullCollectionMembership 
where IsClient = 1
) src
pivot
(
count([Machine])
for [Machine]
in ([LEVEL3], [PC1], [PC2], [PC3], [XP1])
) pvt

Open in new window


Then you can derive that and JOIN on CollectionID, then show the five columns. There should be a 1 or 0 indicating if a row has that Machine or not.

Another way, is to assign a row_number().
select CollectionID
     , [1] AS "Machine1"
     , [2] AS "Machine2"
     , [3] AS "Machine3"
     , [4] AS "Machine4"
     , [5] AS "Machine5"
from 
(
select CollectionID, Name as [Machine] 
      , row_number() over(partition by CollectionID order by [Machine]) rn
from v_FullCollectionMembership 
where IsClient = 1
) src
pivot
(
max([Machine])
for [rn]
in ([1], [2], [3], [4], [5])
) pvt

Open in new window


Again, you would just derive this or put it in a common table expression or view and then JOIN that to the other query as you would any other table...

Best regards and happy coding,

Kevin
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 36898346
Sorry if I missed anything important/pertinent as I was typing my response and did not see any of the interchange above.
0
 
LVL 29

Expert Comment

by:sammySeltzer
ID: 36898374
As stated, if you wish to use UNION query, the number of columns in the first query must match the number of columns in the second query.

In your case, the first query has 8 columns while the second query has only 2.

So, to make it work, you have to assign empty strings if the columns above are strings.

SELECT     v_Advertisement.AdvertisementID,
           v_Advertisement.AdvertisementName,
           v_Package.PackageID,
           v_Package.Name,
           v_Advertisement.ProgramName,
           v_Collection.CollectionID,
           v_Collection.Name AS [Collection Name],
           v_Package.PackageType
FROM   v_Advertisement INNER JOIN
       v_Package ON v_Advertisement.PackageID = v_Package.PackageID INNER JOIN
       v_Collection ON v_Advertisement.CollectionID = v_Collection.CollectionID

UNION ALL

SELECT
         CollectionID, '', '', '', '', '', '',
         Name as 'Machine'
FROM  v_FullCollectionMembership where IsClient = 1 ORDER BY CollectionID, 'Machine'

ORDER BY 2
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 36898452
The sample results do NOT look like a UNION is appropriate. Maybe I am wrong, but it looks like you want to JOIN on the CollectionID and show data on the same line. In your sample, it appears to be pivoted; therefore, that is what I was showing in my comment. I figure the JOIN part is easy after that given you have successfully JOINed other views/tables in your original posted query.
0
 
LVL 2

Accepted Solution

by:
DaemonBarber earned 500 total points
ID: 36899029
left outer join if the number of rows mismatch...
0

Featured Post

Business Impact of IT Communications

What are the business impacts of how well businesses communicate during an IT incident? Targeting, speed, and transparency all matter. Find out more in this infographic.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question