Solved

SQL Join two SQL Statements to get a new resultset.

Posted on 2011-10-01
8
366 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL XPCMDSHELL SQLCMD 1 38
SQL Server how to use a VARIABLE to link tables in a SQL Script? 3 41
What does "Between" mean? 6 44
TDE for SQL Web Edition 1 38
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.
Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
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…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

737 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