如何根据其他值的组合来写入值

时间:2019-03-12 00:10:47

标签: sql sql-server tsql sql-server-2012

示例数据如下:

enter image description here

目标是:

如果我们有相同的ControlNoActionDate(包括时间) 以及Action = 'Changed status''Print Quote'然后是'Print Quote'

的组合

如果我们有相同的ControlNoActionDate(包括时间) 以及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

理想的结果应如下所示: enter image description here

我试图通过以下方式实现这一目标

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

但是它不能给我正确的结果:

enter image description here

1 个答案:

答案 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
;