2

对于要跟踪的每个呼叫,我都有多行数据。数据看起来像这样

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 不为空时,参数为 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     |

任何意见,将不胜感激!

4

3 回答 3

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
于 2012-11-14T03:08:54.807 回答
2

You can use a simple SCALAR SUBQUERY to achieve this.

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;

If you need to make up a site, e.g. "IVR" when there isn't any, then use 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;
于 2012-11-14T04:08:44.673 回答
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上的演示

于 2012-11-14T08:51:24.733 回答