Solved

SQL Join two SQL Statements to get a new resultset.

Posted on 2011-10-01
8
357 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
8 Comments
 
LVL 28

Expert Comment

by:sammySeltzer
Comment Utility
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 28

Expert Comment

by:sammySeltzer
Comment Utility
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
Comment Utility
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
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 59

Expert Comment

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

Expert Comment

by:sammySeltzer
Comment Utility
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 59

Expert Comment

by:Kevin Cross
Comment Utility
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
Comment Utility
left outer join if the number of rows mismatch...
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
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

744 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now