Wrox Programmer Forums
|
SQL Server 2005 General discussion of SQL Server *2005* version only.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the SQL Server 2005 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old June 19th, 2008, 07:26 PM
Friend of Wrox
 
Join Date: Mar 2007
Posts: 205
Thanks: 4
Thanked 0 Times in 0 Posts
Default Combine two queries

I need to combine two queries into one.

Query 1 (main query)


Code:
SELECT               dbo.Job.CompanyJobId, dbo.Job.Name, dbo.Job.Name, dbo.Job.ChangeDate, 
                    dbo.Job.Active,
                            sum(case dbo.SourceType.CompanySourceTypeId WHEN 'MA' then dbo.ProductionEvent.AlternateQuantity ELSE 0 END) AS material,
                          sum(case dbo.SourceType.CompanySourceTypeId WHEN 'PR' THEN dbo.ProductionEvent.Quantity ELSE 0 END) AS production
FROM                    dbo.job 
                          left outer join dbo.Event ON dbo.Job.JobGuid = dbo.Event.JobGuid 
                         left outer join dbo.ProductionEvent on Event.EventGuid = dbo.ProductionEvent.EventGuid
                         left outer join dbo.Product ON dbo.ProductionEvent.ProductGuid = dbo.Product.ProductGuid
                         left outer JOIN dbo.Item ON Event.ItemGuid = dbo.Item.ItemGuid 
                         inner join dbo.Source ON dbo.ProductionEvent.SourceGuid = dbo.Source.SourceGuid
                         inner JOIN dbo.SourceType ON dbo.Source.SourceTypeGuid = dbo.SourceType.SourceTypeGuid
                         left OUTER JOIN dbo.Region ON dbo.Job.RegionGuid = dbo.Region.RegionGuid 
WHERE              dbo.Job.CompanyJobId = 3505048 
                        and(dbo.SourceType.CompanySourceTypeId = 'PR' or dbo.SourceType.CompanySourceTypeId = 'MA')
GROUP BY        dbo.Job.CompanyJobId, dbo.job.name, dbo.Job.ChangeDate, dbo.job.Name, dbo.Job.Active
Result

3505048
SR 434 T-5201 SR 434 T-5201
2007-10-11 16:36:45.647
Y
1314.26 (material qty)
1569.26 (production qty)

(where 1314.26 is sum material and 1569.26 is production)


Query 2


Code:
select    sum(EmployeeLaborEvent.Hours) as hours
from    dbo.job
        left outer join dbo.Event ON dbo.Job.JobGuid = Event.JobGuid 
        Left outer join dbo.EmployeeLaborEvent ON Event.EventGuid = dbo.Employeelaborevent.EventGuid 
WHERE   dbo.Job.CompanyJobId = 3505048
Result:

1647.50 (which are sum of hours, this figure is correct)


Now I try to merge query 2 into Query 1 like this:


Code:
SELECT               dbo.Job.CompanyJobId, dbo.Job.Name, dbo.Job.Name, dbo.Job.ChangeDate, 
                    dbo.Job.Active,
                            sum(case dbo.SourceType.CompanySourceTypeId WHEN 'MA' then dbo.ProductionEvent.AlternateQuantity ELSE 0 END) AS material,
                          sum(case dbo.SourceType.CompanySourceTypeId WHEN 'PR' THEN dbo.ProductionEvent.Quantity ELSE 0 END) AS production,
                             sum(EmployeeLaborEvent.Hours) as hours
FROM               dbo.job 
                          left outer join dbo.Event ON dbo.Job.JobGuid = dbo.Event.JobGuid 
                         left outer join dbo.ProductionEvent on Event.EventGuid = dbo.ProductionEvent.EventGuid
                         left outer join dbo.Product ON dbo.ProductionEvent.ProductGuid = dbo.Product.ProductGuid
                         left outer JOIN dbo.Item ON Event.ItemGuid = dbo.Item.ItemGuid 
                         inner join dbo.Source ON dbo.ProductionEvent.SourceGuid = dbo.Source.SourceGuid
                         inner JOIN dbo.SourceType ON dbo.Source.SourceTypeGuid = dbo.SourceType.SourceTypeGuid
                         left OUTER JOIN dbo.Region ON dbo.Job.RegionGuid = dbo.Region.RegionGuid 

             left outer join dbo.EmployeeLaborEvent ON Event.EventGuid = dbo.Employeelaborevent.EventGuid 

WHERE              dbo.Job.CompanyJobId = 3505048 
                        and(dbo.SourceType.CompanySourceTypeId = 'PR' or dbo.SourceType.CompanySourceTypeId = 'MA')
GROUP BY        dbo.Job.CompanyJobId, dbo.job.name, dbo.Job.ChangeDate, dbo.job.Name, dbo.Job.Active
When I run the query the result is:

3505048
SR 434 T-5201 SR 434 T-5201
2007-10-11 16:36:45.647
Y
1314.26 (material)
1569.26 (production)
NULL (hours)

The material and production stay the same (and is correct). Hours are wrong.

Any clues? Thank you.


 
Old June 20th, 2008, 12:56 AM
Friend of Wrox
 
Join Date: Jun 2008
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Sure. Clues.

In the query where you get the correct sum, you are *ONLY* joining 3 tables. (And I don't see why you are doing LEFT JOINs; I'm pretty sure you would get same results using INNER JOINs, which will be more efficient.)

In the merged query, you are doing an INNER JOIN to two tables not mentioned in the first query, so you are limiting which records you can get much more. Quite honestly, I don't see WHY the limiting affects your SUM, but then I don't know your DB.

OH!!! YES I DO!!!

The WHERE clause in that merged query (and, indeed, in your VERY FIRST QUERY) is basically WIPING OUT the LEFT JOINs and turning them into INNER JOINs!!!!

You CAN NOT use a WHERE clause on the right-side table of a LEFT JOIN without, effectively, converting the LEFT JOIN into an inner join!!

To see why, see this old old post of mine:
http://www.aspmessageboard.com/forum...96501&F=20&P=1

*MAYBE* you can fix it by moving that condition from WHERE to ON, thus:
Code:
SELECT dbo.Job.CompanyJobId, dbo.Job.Name, dbo.Job.Name, dbo.Job.ChangeDate, dbo.Job.Active,
       sum(case dbo.SourceType.CompanySourceTypeId WHEN 'MA' then dbo.ProductionEvent.AlternateQuantity ELSE 0 END) AS material,
       sum(case dbo.SourceType.CompanySourceTypeId WHEN 'PR' THEN dbo.ProductionEvent.Quantity ELSE 0 END) AS production,
       sum(EmployeeLaborEvent.Hours) as hours
FROM   dbo.job 
       left outer join dbo.Event ON dbo.Job.JobGuid = dbo.Event.JobGuid 
       left outer join dbo.ProductionEvent on Event.EventGuid = dbo.ProductionEvent.EventGuid
       left outer join dbo.Product ON dbo.ProductionEvent.ProductGuid = dbo.Product.ProductGuid
       left outer JOIN dbo.Item ON Event.ItemGuid = dbo.Item.ItemGuid 
       inner join dbo.Source ON dbo.ProductionEvent.SourceGuid = dbo.Source.SourceGuid
       inner JOIN dbo.SourceType ON ( 
                dbo.Source.SourceTypeGuid = dbo.SourceType.SourceTypeGuid
            AND dbo.SourceType.CompanySourceTypeId IN ('PR','MA')
            )
       left OUTER JOIN dbo.Region ON dbo.Job.RegionGuid = dbo.Region.RegionGuid 
       left outer join dbo.EmployeeLaborEvent ON Event.EventGuid = dbo.Employeelaborevent.EventGuid 
WHERE  dbo.Job.CompanyJobId = 3505048 
GROUP BY dbo.Job.CompanyJobId, dbo.job.name, dbo.Job.ChangeDate, dbo.job.Name, dbo.Job.Active
But I'm suspicious. And you have several LEFT JOINs in there that seem to have no purpose at all. You never use any fields from the ITEM or REGION or PRODUCT tables. And since they are all LEFT JOINed, that makes them pointless (they aren't restricting any choices in the other tables).

So here's another attempt. Simplified somewhat, including using aliases to make the code more readable (well, to me at least). But really no guarantee, at all.
Code:
SELECT JB.CompanyJobId, JB.Name, JB.Name, JB.ChangeDate, JB.Active,
       sum(case ST.CompanySourceTypeId WHEN 'MA' then PEV.AlternateQuantity ELSE 0 END) AS material,
       sum(case ST.CompanySourceTypeId WHEN 'PR' THEN PEV.Quantity ELSE 0 END) AS production,
       sum(ELE.Hours) as hours
FROM   dbo.job AS JB
       left outer join dbo.Event AS EV ON JB.JobGuid = EV.JobGuid 
       left outer join (
          dbo.ProductionEvent AS PEV inner join dbo.Source AS S
          ON PEV.SourceGuid = S.SourceGuid 
          ) on EV.EventGuid = PEV.EventGuid
       inner join (
           dbo.Source inner JOIN dbo.SourceType AS ST 
           ON ( S.SourceTypeGuid = ST.SourceTypeGuid AND ST.CompanySourceTypeId IN ('PR','MA') )
           ) ON PEV.SourceGuid = S.SourceGuid
       left outer join dbo.EmployeeLaborEvent AS ELE ON EV.EventGuid = ELE.EventGuid 
WHERE  JB.CompanyJobId = 3505048 
GROUP BY JB.CompanyJobId, JB.name, JB.ChangeDate, JB.Name, JB.Active
You may have to resort to doing this the same way I showed you with the other one. Create a temp table and then join to it. Not sure.
 
Old June 20th, 2008, 07:21 AM
Friend of Wrox
 
Join Date: Mar 2007
Posts: 205
Thanks: 4
Thanked 0 Times in 0 Posts
Default

Input Appreciated.....

1. First query gives error:
Server: Msg 107, Level 16, State 2, Line 1
The column prefix 'S' does not match with a table name or alias name used in the query.

2. Second query renders same result (material and production qty's are ok, hours are still NULL)
 
Old June 20th, 2008, 02:21 PM
Friend of Wrox
 
Join Date: Jun 2008
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Okay, so do like we did before...

Create a #temp table with the results of the first query and then join it to the other tables for the 2nd query.
 
Old June 24th, 2008, 02:44 PM
SQLScott's Avatar
Wrox Author
 
Join Date: Dec 2004
Posts: 338
Thanks: 0
Thanked 2 Times in 2 Posts
Default

Or instead of a #temp table, why not use a CTE?

========================
Scott Klein
Author of:
Professional SQL Server 2005 XML
Professional WCF Programming: .NET Development with the Windows Communication Foundation
Professional LINQ
========================
 
Old June 24th, 2008, 04:43 PM
Friend of Wrox
 
Join Date: Jun 2008
Posts: 1,649
Thanks: 3
Thanked 141 Times in 140 Posts
Default

Why not? Because table expressions didn't exist when I learned SQL Server and I'm stuck in my old ways? <grin/>
 
Old June 24th, 2008, 09:42 PM
SQLScott's Avatar
Wrox Author
 
Join Date: Dec 2004
Posts: 338
Thanks: 0
Thanked 2 Times in 2 Posts
Default

lol...yeah..old habits are hard to break. I still use the /* */ to comment sql code...

========================
Scott Klein
Author of:
Professional SQL Server 2005 XML
Professional WCF Programming: .NET Development with the Windows Communication Foundation
Professional LINQ
========================





Similar Threads
Thread Thread Starter Forum Replies Last Post
Combine sql queries snufse SQL Server 2005 16 June 17th, 2008 03:47 PM
Help: Need to combine multiple IF queries scotts SQL Server 2005 1 April 14th, 2008 07:54 PM
Combining Queries or results from 2 queries Ford SQL Server 2000 24 November 7th, 2005 08:54 PM
combine 2 queries collie SQL Server 2000 2 November 29th, 2004 03:09 PM
Combine queries lryckman Access VBA 2 May 11th, 2004 11:38 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.