当连接似乎不起作用时,如何将两个选择压缩在一起

时间:2017-03-10 14:40:08

标签: sql sql-server join

我感觉这是一个超级基本的问题,但我错过了一些东西。我有两个问题,第一个是

SELECT 

[User Name]

,sum(datediff(SECOND,[signon time],[Signoff Time])) as [Shift Seconds]
,sum([Signon Duration]) as [Signon]
,sum([Total Logon Duration]) as [logged on seconds]
,sum([Total Activation Duration]) as [active seconds]
,sum([Pre Signoff DND Duration]) as [DND]
,sum([Total Idle Duration]) as [Idle]
,sum([Total Pickup Duration]) as [Pickup]
,sum([Pre Signoff DND Duration]) as [Pre Signoff DND Duration]

From 

[iPR].[dbo].[AgentSignonStatus]

where 

[Signon Time] between '2017-03-01' and '2017-03-08'




group by [User Name]
order by [User Name]

提供此输出

Output 1

和此查询

SELECT

[agent name]

,sum(iif([Type] in ('Normal operator call') ,1,0)) as [Calls Answered]
,sum(iif([Type] in ('Normal operator call'),[connected (secs)],NULL)) AS [Total Duration of Answered Calls]

From

 InboundCallsView 

 where 

[Start Time] between '2017-03-01' and '2017-03-08'

 group by [Agent Name]

 order by [Agent Name]

给出了这个输出

output 2

我已尝试在[用户名] = [代理商名称]右连接和UNION上加入代理登录到inboundcalls。我也在SELECT中尝试了一个SELECT,但无论我尝试什么似乎都会将一个字段或另一个字段相乘多次。我猜它与多对一的情况有关,但我基本上都坚持这一点。我想看到的只是 desired output

但我完全不知道如何实现它。

2 个答案:

答案 0 :(得分:1)

您可以将查询加入为派生表(子查询)或使用common table expressions,如下所示:

with cte as (
  SELECT 
    [User Name]
    ,sum(datediff(SECOND,[signon time],[Signoff Time])) as [Shift Seconds]
    ,sum([Signon Duration]) as [Signon]
    ,sum([Total Logon Duration]) as [logged on seconds]
    ,sum([Total Activation Duration]) as [active seconds]
    ,sum([Pre Signoff DND Duration]) as [DND]
    ,sum([Total Idle Duration]) as [Idle]
    ,sum([Total Pickup Duration]) as [Pickup]
    ,sum([Pre Signoff DND Duration]) as [Pre Signoff DND Duration]
  From [iPR].[dbo].[AgentSignonStatus]
  where [Signon Time] between '2017-03-01' and '2017-03-08'
  group by [User Name]
  --order by [User Name]
)
, inbound as (
  SELECT
    [agent name]
    ,sum(iif([Type] in ('Normal operator call') ,1,0)) as [Calls Answered]
    ,sum(iif([Type] in ('Normal operator call'),[connected (secs)],NULL)) 
      AS [Total Duration of Answered Calls]
  From InboundCallsView 
  where [Start Time] between '2017-03-01' and '2017-03-08'
  group by [Agent Name]
  --order by [Agent Name]
)
select cte.*
  , inbound.[Calls Answered]
  , inbound.[Total Duration of Answered Calls]
from cte
  inner join inbound
    on cte.[User Name] = inbound.[agent name]
order by cte.[User Name]

如果你需要一个不同于inner join的其他联接,那么它应该是一个简单的修复。看起来您应该基于使用相同的where子句进行1:1匹配。

答案 1 :(得分:0)

我认为大致应该遵循这个机制:

select isnull(a.username, b.agentname), *
from
(...query 1 sql...) a
full outer join
(...query 2 sql...) b on a.username = b.agentname