• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 381
  • Last Modified:

SQL Join two SQL Statements to get a new resultset.

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
whorsfall
Asked:
whorsfall
1 Solution
 
sammySeltzerCommented:
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
 
sammySeltzerCommented:
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
 
whorsfallAuthor Commented:
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
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
Kevin CrossChief Technology OfficerCommented:
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
 
Kevin CrossChief Technology OfficerCommented:
Sorry if I missed anything important/pertinent as I was typing my response and did not see any of the interchange above.
0
 
sammySeltzerCommented:
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
 
Kevin CrossChief Technology OfficerCommented:
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
 
DaemonBarberCommented:
left outer join if the number of rows mismatch...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now