SQL:从一行中获取一个值,并从同一个表中的另一行更新另一个值

时间:2017-06-26 11:55:09

标签: sybase

我的表格如下:

EFFECTIVE_DATE    POLICY_ID    PLAN_ID    TOTAL    CODE
01/31/2017        A100         R          0.20     000
01/31/2017        A100         M          100.00   000
01/31/2017        A100         W          0.00     000

我需要取PLAN_ID = R所在的行并将TOTAL添加到PLAN_ID = M

所在的行

结果应如下所示:

EFFECTIVE_DATE    POLICY_ID    PLAN_ID    TOTAL    CODE
01/31/2017        A100         M          100.20   000
01/31/2017        A100         W          0.00     000

1 个答案:

答案 0 :(得分:0)

设置一些样本数据:

use tempdb
go

if object_id('data') is not null
        drop table data
go

create table data
(EFFECTIVE_DATE datetime    not NULL
,POLICY_ID      varchar(10) not NULL
,PLAN_ID        char(1)     not NULL
,TOTAL          smallmoney  not NULL
,CODE           varchar(3)  not NULL
)
go

set nocount on
go

insert data values ('01/31/2017','A100','R',0.20,'000')
insert data values ('01/31/2017','A100','M',100.00,'000')
insert data values ('01/31/2017','A100','W',0.00,'000')
go

执行所需的更新/删除:

update  data
set     TOTAL = t1.TOTAL + t2.TOTAL

from    data t1,
        data t2

where   t1.EFFECTIVE_DATE = t2.EFFECTIVE_DATE
and     t1.POLICY_ID      = t2.POLICY_ID
and     t1.PLAN_ID        = 'M'
and     t2.PLAN_ID        = 'R'

--

delete  data
where   PLAN_ID = 'R'

--

select  convert(varchar(10),EFFECTIVE_DATE,101) as EFFECTIVE_DATE,
        POLICY_ID,
        PLAN_ID,
        TOTAL,
        CODE
from    data
order by EFFECTIVE_DATE, POLICY_ID, PLAN_ID
go

 EFFECTIVE_DATE POLICY_ID  PLAN_ID TOTAL    CODE
 -------------- ---------- ------- -------- ----
 01/31/2017     A100       M         100.20 000
 01/31/2017     A100       W           0.00 000

如果给定的EFFECTIVE_DATE + POLICY_ID对可以存在多个“R”记录:

truncate table data
go

insert data values ('01/31/2017','A100','R',0.20,'000')
insert data values ('01/31/2017','A100','R',0.11,'000')
insert data values ('01/31/2017','A100','M',100.00,'000')
insert data values ('01/31/2017','A100','W',0.00,'000')
go

update  data
set     TOTAL = t1.TOTAL + (select      sum(t2.TOTAL)
                                from    data t2
                                where   t2.EFFECTIVE_DATE = t1.EFFECTIVE_DATE
                                and     t2.POLICY_ID      = t1.POLICY_ID
                                and     t2.PLAN_ID        = 'R')
from    data t1
where   t1.PLAN_ID = 'M'

--

delete  data
where   PLAN_ID = 'R'

--

select  convert(varchar(10),EFFECTIVE_DATE,101) as EFFECTIVE_DATE,
        POLICY_ID,
        PLAN_ID,
        TOTAL,
        CODE
from    data
order   by EFFECTIVE_DATE, POLICY_ID, PLAN_ID
go

 EFFECTIVE_DATE POLICY_ID  PLAN_ID TOTAL    CODE
 -------------- ---------- ------- -------- ----
 01/31/2017     A100       M         100.31 000
 01/31/2017     A100       W           0.00 000

注意:

  • 第二个查询适用于单个和多个“R”记录(根据EFFECTIVE_DATE + POLICY_ID对)
  • 用户应添加其他代码以提供事务管理和错误处理