?
Solved

SQL Join two SQL Statements to get a new resultset.

Posted on 2011-10-01
8
Medium Priority
?
375 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
 
LVL 1

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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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 2000 total points
ID: 36899029
left outer join if the number of rows mismatch...
0

Featured Post

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
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.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

650 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