示例数据如下:
目标是:
如果我们有相同的ControlNo
和ActionDate
(包括时间)
以及Action = 'Changed status'
和'Print Quote'
然后是'Print Quote'
如果我们有相同的ControlNo
和ActionDate
(包括时间)
以及Action = 'Changed status'
和'Reason for quote'
然后是'Changed Status'
查询示例:
declare @TempTable table (
Name varchar(50),
ControlNo int,
PolicyNumber varchar(50),
Action varchar(max),
ActionDate datetime
)
insert into @TempTable values
('Jim',54321, NULL, 'Changed status','2019-01-29 09:56:12.820' ),
('Jim',54321, NULL, 'Print Quote','2019-01-29 09:56:12.820' ),
('Brian',12345, NULL, 'Changed status','2019-02-15 11:18:07.356' ),
('Brian',12345, NULL, 'Reason for quote','2019-02-15 11:18:07.356')
select * from @TempTable
我试图通过以下方式实现这一目标
select
name,
ControlNo,
PolicyNumber,
case
when action in( 'Changed status','Print Quote') then 'Print Quote'
when action in ('Changed status', 'Reason for quote') then 'Changed Status'
else Action end as Action
from @TempTable
group by
name,
ControlNo,
PolicyNumber,
Action
但是它不能给我正确的结果:
答案 0 :(得分:1)
请注意,“ IN”条件相当于“ OR”。
可以提供帮助的代码:
SELECT a.Name,a.ControlNo,a.PolicyNumber,a.Action,a.ActionDate
FROM (
SELECT t.Name,t.ControlNo,t.PolicyNumber
,CASE
WHEN t2.Action = 'Print Quote' THEN 'Print Quote'
WHEN t2.Action = 'Reason for quote' THEN 'Changed status'
END AS [Action]
,t.ActionDate
FROM @TempTable t
LEFT JOIN @TempTable t2 ON t2.ControlNo = t.ControlNo AND t2.ActionDate = t.ActionDate AND t2.Action <> t.Action
WHERE t.Action = 'Changed status'
) a
GROUP BY a.Name,a.ControlNo,a.PolicyNumber,a.Action,a.ActionDate
;