SQL:比较来自两个不同选择的两个结果

时间:2018-10-17 20:54:03

标签: sql-server

我需要确定我们的顾问是否正确记录了他们的工作。为此,我有两个不同的来源:一个包含来电,另一个在我们的客户系统中其日志。

呼叫链接到电话号码,日志链接到客户号码。对于这两个来源中的每一个,我都有一个选择,可为我提供每个顾问的周号和(客户/电话)号的不同组合的数目,以查找整年的唯一“周通话”总数。但是,如何将唯一日志的结果与唯一调用相除?而且对于奖金难度,没有临时表格(在Excel中无效)

选择#1

SELECT 
count(distinct(concat(datepart(ww,call_datetime),phonenumber))) as 
calls,consultant
FROM calltabel
group by consultant

选择#2

SELECT 
count(distinct(concat(datepart(ww,log_datetime),phonenumber))) as 
logs,consultant
FROM logtabel
group by consultant

结果

选择#1

consultant    calls
eric          10
kimmie        20

选择#2

consultant    logs
eric          5
kimmie        20

组合结果应该是

consultat    calls    logs     result
eric         10        5        0.5
kimmie       20       20        1.0  

2 个答案:

答案 0 :(得分:1)

您可以像这样加入查询

select t1.consultant, calls, logs, logs/calls as result
(SELECT 
count(distinct(concat(datepart(ww,call_datetime),phonenumber))) as 
calls,consultant
FROM calltabel
group by consultant) as t1
inner join
(SELECT 
count(distinct(concat(datepart(ww,log_datetime),phonenumber))) as 
logs,consultant
FROM logtabel
group by consultant) as t2 on t1.consultant=t2.consultant

或者您可以这样做:

select t1.consultant, calls, logs, logs/calls as result from
(
SELECT calltabel.consultant,
count(distinct(concat(datepart(ww,call_datetime),phonenumber))) as calls,
count(distinct(concat(datepart(ww,log_datetime),phonenumber))) as logs    
FROM calltabel 
inner join logtabel on logtabel.consultant= calltabel.consultant
group by calltabel.consultant
)

答案 1 :(得分:1)

You can do inner join:

Select callTable.Consultant, callTable.calls, logTable.logs, logTable.logs/callTable.logs as ‘Result’ from (SELECT 
count(distinct(concat(datepart(ww,call_datetime),phonenumber))) as 
calls,consultant
FROM calltable
group by consultant) as callTable, (SELECT 
count(distinct(concat(datepart(ww,log_datetime),phonenumber))) as 
logs,consultant
FROM logtable
group by consultant) as logTable

Where logTable.consultant = callTable.consultant;