SQL使用另一个数据更新一个单行表

时间:2017-02-23 16:53:50

标签: sql sql-server

我有两张桌子。第一个在12个月内进行所有运动,第二个在同一时间内进行索赔。当我从第一个表运行以下查询时,我有10条记录。当然,还有其他记录具有不同的移动次数(例如:7,23,2次移动):

select t.cod_suc
      ,t.cod_ramo_comercial
      ,t.Poliza
      ,t.Item
      ,t.id_pv
from temp_portafolio_personal_accidents as t
where t.cod_suc = 2
      and t.cod_ramo_comercial = 46
      and t.Poliza = 50283
      and t.Item = 1
      and t.id_pv = 788383;

enter image description here

使用第二个查询,对于第二个表,我有以下结果:

select c.cod_suc
      ,c.cod_ramo_comercial
      ,c.[No. Policy]
      ,c.Item
      ,c.[ID Incident]
      ,max(c.id_pv) as id_pv
      ,count(distinct [No. Incident]) as 'Conteo R12'
from #claims as c
where c.[ID Incident] = 343632
group by c.cod_suc
        ,c.cod_ramo_comercial
        ,c.[No. Policy]
        ,c.Item
        ,c.[ID Incident];

enter image description here

现在,我需要更新第一个表但只更新一个记录。我正在使用以下查询,但所有记录都在更新。当我总结结果时,我有10个但只是一个声明,正如第二个查询所示。

update p
set [No. Siniestros R12] = b.[Conteo R12]
from temp_portafolio_personal_accidents p
    left join
     (select c.cod_suc
            ,c.cod_ramo_comercial
            ,c.[No. Policy]
            ,c.Item
            ,c.[ID Incident]
            ,max(c.id_pv) as id_pv
            ,count(distinct [No. Incident]) as 'Conteo R12'
      from
           #claims as c
      where c.[ID Incident] = 343632
      group by c.cod_suc
              ,c.cod_ramo_comercial
              ,c.[No. Policy]
              ,c.Item
              ,c.[ID Incident]
     ) b
        on p.id_pv = b.id_pv
           and p.cod_suc = b.cod_suc
           and p.cod_ramo_comercial = b.cod_ramo_comercial
           and p.Poliza = b.[No. Policy]
           and p.Item = b.Item
where p.id_pv = 788383;

1 个答案:

答案 0 :(得分:1)

您可以使用具有ROW_NUMBER()功能的CTE来执行此操作。简单的例子:

DECLARE @TABLE AS TABLE (Testing INT, Testing2 VARCHAR(55), Testing3 BIT);
INSERT INTO @TABLE VALUES (1, '1', 1);
INSERT INTO @TABLE VALUES (1, '1', 1);
INSERT INTO @TABLE VALUES (1, '1', 1);
INSERT INTO @TABLE VALUES (1, '1', 1);
INSERT INTO @TABLE VALUES (1, '1', 1);
INSERT INTO @TABLE VALUES (1, '1', 1);
INSERT INTO @TABLE VALUES (1, '1', 1);
INSERT INTO @TABLE VALUES (1, '1', 1);

WITH CTE AS 
(
    SELECT
         ROW_NUMBER() OVER (ORDER BY Testing) AS RowID
        ,Testing
        ,Testing2
        ,Testing3
    FROM @TABLE
)
UPDATE CTE
SET Testing = 2, Testing2 = '2', Testing3 = 0
WHERE RowID = 1
;
SELECT * FROM @TABLE
;