案例陈述是答案

时间:2012-11-14 03:03:16

标签: sql case

我正在尝试跟踪的每个呼叫都有多行数据。数据看起来像这样

Call_ID | site | Agent_key | starttime | exit_reason
----------------------------------------------------
1234     |   7   |           |     1     | transfer
1234     |   3   |  1010101  |     15    | transfer
1234     |   7   |  2121212  |     302   | transfer
1234     |   5   |  3232323  |     680   | transfer

我想创建一个名为“first_site”的列。当starttime为min(starttime)且Agent_key不为null时,参数为site。 (如果Agent_key为空,则表示呼叫仍在呼叫中心系统中,因此我不关心在那里代表哪个站点。

结果看起来像

Call_ID | site | Agent_key | starttime | exit_reason | first_site |
-------------------------------------------------------------------
1234     |   7   |           |     1     | transfer    |      3     |
1234     |   3   |  1010101  |     15    | transfer    |      3     |
1234     |   7   |  2121212  |     302   | transfer    |      3     |
1234     |   5   |  3232323  |     680   | transfer    |      3     |

任何建议都将不胜感激!

3 个答案:

答案 0 :(得分:2)

希望这会有所帮助

Select t.*, x.first_site
From YourTable t
Inner Join

(Select Call_Id,Min(site) As first_site
From YourTable
Where agent_key is not null -- Where Len(agent_key) > 0
Group By Call_Id)X

On t.Call_Id = x.Call_Id

答案 1 :(得分:2)

您可以使用简单的SCALAR SUBQUERY来实现此目的。

select outr.*, (select TOP 1 site
                 from tbl
                where call_id=outr.call_id
                  and agent_key is not null
             order by starttime asc) first_site
  from tbl outr;

如果您需要组建网站,例如如果没有“IVR”,则使用ISNULL()

select outr.*, ISNULL((select TOP 1 site
                 from tbl
                where call_id=outr.call_id
                  and agent_key is not null
             order by starttime asc), 'IVR') first_site
  from tbl outr;

答案 2 :(得分:1)

我的查询在没有附加表连接的情况下执行。;)

SELECT Call_ID, site, Agent_key, starttime, exit_reason,
       CASE WHEN MIN(CASE WHEN Agent_key IS NOT NULL THEN starttime END) OVER () = starttime 
            THEN site 
            ELSE CASE WHEN MIN(CASE WHEN Agent_key IS NOT NULL THEN starttime END) OVER () != starttime
                      THEN MIN(CASE WHEN Agent_key IS NOT NULL THEN site END) OVER () END
       END AS first_site
FROM dbo.your_table

SQLFiddle上的演示

相关问题