2017-02-23 83 views
1

我有兩個表。第一次在12個月內有所有變動,第二次在同一段時間登記。當我從第一個表中運行以下查詢時,我有10條記錄。當然,還有其他的記錄具有不同數目的動作(例如:7,23,2個運動):SQL使用另一個數據更新一個單行表

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

你的表temp_portafolio_personal_accidents有一個ID(其唯一行標識符)? – scaisEdge

+1

你能指定你想更新哪一個「一條記錄」嗎?他們中的任何一個會做? – DVT

+0

爲什麼使用「左連接」?如果沒有相應的記錄,那麼你會設置[No. ... R12]爲NULL? – DVT

回答

1

您可以使用CTE與ROW_NUMBER()功能來做到這一點。簡單的例子:

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 
; 
相關問題