提取在不同日期修改的记录

时间:2018-08-08 16:49:34

标签: sql sql-server date

我有一个名为t1的表,其中包含以下字段:codLoan,codOp,codCau,action和dateExec。可以将操作字段假定为三个值:“ I”(插入),“ M”(修改)或“ C”(取消)。

我的记录可以在不同的日期进行修改,因此我可以有两个记录具有相同的codLoan,但dateExec的值不同。

我必须提取在不同的dateExec中具有相同codLoan和不同Action(I或M)的所有记录。

例如:

codLoan=1
dateExec= '2018/08/08'
action='I'

codLoan=1
dateExec= '2018/08/08'
action='M'

codLoan=2
dateExec= '2018/08/07'
action='I'

codLoan=2
dateExec= '2018/08/08'
action='M'

结果:codLoan = 2,dateExec ='2018/08/08'


我尝试了此查询,但是它提取了所有带有Action ='I'和Action ='M'的记录。

select codLoan, dateExec
from t1
where Action in ('I','M');

如何修复我的代码?

4 个答案:

答案 0 :(得分:2)

也许您想要:

select t.*
from table t
where exists (select 1 
              from table t1 
              where t1.codLoan = t.codLoan and 
                    t1.dateExec <> t.dateExec and 
                    t1.action <> t.action
             );

答案 1 :(得分:2)

使用联接:

select b.*
from mytable a
join mytable b on b.codLoan = a.codLoan
    and b.dateExec > a.dateExec
    and b.action != a.action
    and b.action in ('I','M')
where a.action in ('I','M')

这将返回最后操作和日期。

答案 2 :(得分:1)

另一个选择

select codLoan
     , dateExec = min(dateExec)
from t1
where Action in ('I','M')
Group By codLoan
Having min(dateExec)<>max(dateExec)

答案 3 :(得分:0)

declare @t table
(
    codLoan  int,
    dateExec date,
    [action] char(1)
);

insert into @t values
(1, '2018-08-08', 'I'),
(1, '2018-08-08', 'M'),
(2, '2018-08-07', 'I'),
(2, '2018-08-08', 'M');

with diff as
(
    select x.*
    from
    (
        select
            *,
            cnt1 = count(*) over (partition by codLoan, dateExec
                                  order by codLoan) ,
            cnt2 = count(*) over (partition by codLoan, [action], dateExec
                                  order by codLoan),
            rnum = row_number() over (partition by codLoan
                                      order by dateExec desc)
        from @t
    ) x
    where cnt1 = cnt2 
)
select codLoan, dateExec
from diff
where rnum = 1
order by codLoan, dateExec;