Solved

SQl union query

Posted on 2007-03-29
2
243 Views
Last Modified: 2010-08-05
If I run the individual queries from the following union, i get the expected result.  However, if I run the union as is, I get an incorrect result.  Can anyone tell me why?  Also, the second query in the union takes 30 seconds to run - why's that?

query:

SELECT
Count(Calls) as calls, sum(booking) as booking, count(calls)/sum(Booking)+ count(calls) as hitrate
FROM

(SELECT
Count(CallLogger.CallLoggerId) AS Calls, 0.0 as booking
FROM
RIO.CallLogger.dbo.CallLogger [CallLogger]
INNER JOIN RIO.CallLogger.dbo.Extensions [Extensions] ON [CallLogger].Extension1 = [Extensions].Extension
WHERE
DateDiff(y, CallLogger.[Date], getdate()) = 0
AND [CallLogger].CallType=1
AND [Extensions].[Group]='Telesales'

UNION

SELECT
0.0 as calls,
SUM(Calls.Booking) AS Booking
FROM
RFVSQL.RFPUB.dbo.Calls [Calls] INNER JOIN RFVSQL.RFPUB.dbo.Users [Users] ON [Calls].UserId = [Users].UserId
WHERE
DateDiff(y, [Calls].DateTimeCreated, getdate()) = 0
AND [Users].DepartmentId=11) X

Thanks
Lapchien
0
Comment
Question by:Lapchien
2 Comments
 
LVL 32

Accepted Solution

by:
Daniel Wilson earned 500 total points
ID: 18814638
Your entire statement returns 2 for Count(Calls), right?  Is that your problem?

The top-level SELECT should say Sum(Calls).  You counted the calls in the first query & you knew the second section was returning 0 calls.  You want to add the 0 for the 2nd block to the number in the 1st block.

Not sure why the 2nd block takes as long as it does.  How many rows are in [calls]?  For this query, you should have a couple indices:

Create Index IX_CALLS_User_DT on [Calls] (UserID, DateTimeCreated)
go
Create Index IX_Users_User_Dept on [Users] (UserID, DepartmentID)
go

If you already have indices like that, and the tables are not huge it should not take so long.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

In database programming, custom sort order seems to be necessary quite often, at least in my experience and time here at EE. Within the realm of custom sorting is the sorting of numbers and text independently (i.e., treating the numbers as number…
I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial

713 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