I am new to sql and I have come across a problem on joining 3 tables.
I have 3 tables
1) USER_MASTER (userid,fname,lname)
This is the call center agent table
2) CALL_MASTER (callid, customername,phone,userid,calltype)
this is where the customer calls go into , user id is used to link which agent
picked up the call , calltype is the outcome of the call
3) CALL_TYPE_MASTER as
calltype typename
1 transferred
2 routed
3 disconnected
I want to list it like this
Agent name Transferred routed disconnected
Balang Hector 7 1 2
Bonus Donna 0 1 2
Dalino Marie 8 1 1
Dela Cruz 0 0 1
I tried this query:
SELECT
USER_MASTER.FirstName,COUNT(CALL_MASTER.CallType) as Transferred
FROM
(USER_MASTER LEFT JOIN CALL_MASTER ON CALL_MASTER.UserID=USER_MASTER.USERID)
WHERE
CALL_MASTER.CallType=1
GROUP BY
USER_MASTER.FirstName
But the problem is I have to list another row as “routed” and “transferred”, but that would mean changing the where clause, and it would obviously not output “0” if it is not found.
This is, of course, a fairly standard
PIVOTquery. Here’s a version more idiomatic for SQL Server:SQL Fiddle Demo
The aggregate appears to be happening before the join to
User_Master, so the query should be able to use indices to fulfill theCOUNT(*). Unfortunately there’s no way to automatically populate column aliases – you’d need dynamic SQL for that.EDIT:
Explanations –
This subquery is getting a list of columns over which the aggregate will be grouped and run. You can do any conditions for range checks, and similar. The intent is that the query should be what you’d write for a
GROUP BY… just without that clause, and an aggregate.This clause is telling the system “for the previous table-reference, run the given aggregate over the listed column, and for every change in the other (potentially different) column, put the result in a new column”. There are some caveats:
GROUP BYclauseINclause must contain all values your subquery returns, but can also have columns without results. Leaving out[2]will get a runtime error, but adding[4]just gets you a column with0sFORclause is character, you don’t use quotes around the values.An alias for the result table (
Pivotedhere) is required, and is in effect for all columns involved. There’s noCall_Master.userIdcolumn at this point in the query.JOIN User_Master
ON User_Master.userId = Pivoted.userId
… And finally, a join to
User_Masterto translate user ids to names. Note that, because the aggregate happens “inside” the reference generated as part of thePivotquery, you don’t have to worry about strange things happening to the rest of your data.