大家好日子。我一直无法提出解决方案,正在寻求任何帮助。我有一个表格,我想添加一个列:
ID Time_Stamp Activity_Log
1254 6/1/2013 8:00:00AM 'Ticket was opened by user A'
1254 6/2/2013 8:20:00AM 'Comment was logged by user B'
1254 6/4/2013 8:25:00AM '**Ticket was transferred to Group 1**'
1254 6/7/2013 8:50:00AM 'Comment was logged by user B'
1254 6/11/2013 10:00:00AM 'Comment was logged by user C'
1254 6/12/2013 12:00:00PM '**Ticket was transferred to Group 2**'
7589 6/3/2013 11:00:00PM 'Ticket was opened by user A'
7589 6/5/2013 1:00:00PM 'Comment was logged by user C'
7589 6/7/2013 2:00:00PM 'Resolution provided by user C'
7589 6/11/2013 5:00:00PM 'Ticket resolved by user C'
8526 6/3/2013 7:00:00PM 'Ticket opened by user D'
8526 6/4/2013 2:00:00PM '**Ticket was transferred to Group 2**'
8526 6/5/2013 1:00:00PM 'Comment was logged by user G'
8526 6/8/2013 5:00:00PM '**Ticket was resolved by user C**'
以下是我希望新专栏“Group”的样子:
ID Time_Stamp Activity_Log Group
1254 6/1/2013 8:00:00AM 'Ticket was opened by user A' NULL
1254 6/2/2013 8:20:00AM 'Comment was logged by user B' NULL
1254 6/4/2013 8:25:00AM '**Ticket was transferred to Group 1**' Group 1
1254 6/7/2013 8:50:00AM 'Comment was logged by user B' Group 1
1254 6/11/2013 10:00:00AM 'Comment was logged by user C' Group 1
1254 6/12/2013 12:00:00PM '**Ticket was transferred to Group 2**' Group 2
7589 6/3/2013 11:00:00PM 'Ticket was opened by user A' NULL
7589 6/5/2013 1:00:00PM 'Comment was logged by user C' NULL
7589 6/7/2013 2:00:00PM 'Resolution provided by user C' NULL
7589 6/11/2013 5:00:00PM 'Ticket resolved by user C' NULL
8526 6/3/2013 7:00:00PM 'Ticket opened by user D' NULL
8526 6/4/2013 2:00:00PM '**Ticket was transferred to Group 2**' Group 2
8526 6/5/2013 1:00:00PM 'Comment was logged by user G' Group 2
8526 6/8/2013 5:00:00PM '**Ticket was resolved by user C**' Group 2
如果Activity_Log是LIKE'%xx%',我想用字符串添加这个组列,并且在基于ID和Time_Stamp之后的每一行中添加。某些ID在activity_log中不具有该语言,并且Group列对于所有行都将为NULL。对于那些,我想在activity_log是LIKE'%transfer to Group x%'时开始,并在activity_log像'%Transfer to Group x%'或'%ticket was resolved%'时结束。我试图使用OVER(分区依据)来编写一个查询,但是我没有成功。
由于
答案 0 :(得分:2)
您可以使用“累积最大值”功能执行此操作。大多数支持窗口函数的数据库都支持此功能,但SQL Server 2012之前的SQL Server除外。
这是方法:
select t.id, t.Time_Stamp, t.Activity_Log,
MAX(GroupName) over (partition by id order by TimeStamp) as "Group"
from (select t.*,
(case when Activity_Log like '%transferred to Group%'
then left(RIGHT(Activity_Log, 9), 7)
end) as GroupName
from t
) t;
如果您确实想要将其添加为列,则需要更改表以添加列,然后使用update
语句。
如果您的数据库不支持累积总和,您仍然可以使用相关子查询来完成工作:
select t.id, t.Time_Stamp, t.Activity_Log,
(select left(RIGHT(t2.Activity_Log, 9), 7)
from t t2
where t2.id = t.id and
t2.TimeStamp <= t.TimeStamp and
Activity_Log like '%transferred to Group%'
order by t2.TimeStamp desc
limit 1
) as "Group"
from t;
答案 1 :(得分:0)
我会使用Gordon Linoff's
解决方案,但如果您想要存储ALTER TABLE
,可以添加所需的列,如果您只想显示信息{{1}也很好。
SELECT