2016-10-26 31 views
0

我有兩個包含6列的表格,在一個表格(我想更新的表格)中,前三列已經填充,其他三列我只是這樣做的'空虛。從另一個表格數據更新表中的多個列(包括空值)

彙總表

Number, ID, height, weight, volume, density 
1  1  5  
2  2  5 
3  3  12 

我有另一個表完全填充,其中相同的ID被使用,但其他數據的波動並沒有高度

日表

Number, ID, name, weight, volume, density 
1  1 c3  23    10 
2  2 c17 24.2 1  5 
3  3 c12 22  2  6 
4  1 c3  21  2 
5  2 c17 25    8 

我想從Daily表中獲取最後的體重,體積,密度值,並使用它們來填充Summary表中的那些列。兩個表都有數千個條目,每天有一個接近一百萬條。

結果應該是彙總表更改

Number, ID, height, weight, volume, density 
1  1  5  21  2 
2  2  5  25    8 
3  3  12  22  2  6 

我能做到這一點位使用的信息,我從this question了一點,但我想同時做這一切。 請協助。

+0

如何識別日常表中的「最後」行?我沒有看到任何時間戳或類似的東西 –

+0

@a_horse_with_no_name它們是行數,抱歉應該是六列現在我明白你的意思了,我會編輯 – Kilisi

回答

3

事情是這樣的:

update summary 
    set weight = t.weight, 
     volume = t.volume, 
     density = t.density 
from (
    select distinct on (id) id, weight, volume, density 
    from daily 
    order by id, number desc 
) t 
where t.id = summary.id; 

內選擇將只能從日常表,每個ID最高的「數字」返回行。對於看

在線例如解決的其他方式:http://rextester.com/AWT29305

+0

適合我的需求,很好很簡單 – Kilisi

1

你可以使用一個窗口funtion讓你的日常表中的每個ID的最新條目。我已經在SQL Server中測試過了,但是我相信在這種情況下postgres的語法是一樣的。

With LatestDaily As 
(
    select * 
    from (
    Select RANK() OVER (Partition By ID ORDER BY Number DESC) as r, * 
    From Daily 
) t 
    where t.r = 1 
) 
Update summary s 
    Set Weight = d.Weight, Volume = d.Volume, Density = d.Density 
From LatestDaily d 
where s.ID = d.ID; 
+0

Postgres需要' ;'最後,不是在開始。在使用'distinct on()'而不是窗口函數時,Postgres中的「每個組的最大n值」問題通常更快。 Postgres中帶有連接的'update'語法是不同的。你不應該**在'from'子句中重複目標表。 –

+0

好的。謝謝!我想知道sql服務器是否具有與postgres的distinct on()相同的功能。這是一個很好的功能。 – SteveR

+0

我冒昧地修復了您的陳述中的語法錯誤。 –

1

試試這個:

with Daily as (
select d.number, d.Id, d.weight, d.volume, d.density 
From daily d 
join (select id, max(number) from daily group by ID) d2 on d.number = d2.number 
) 
update Summary 
set weight = d2.weight 
, volume = d2.volume 
, density = d2.density 
from Daily d2 
where id = d2.id 
and 
(weight<> d2.weight OR 
volume <> d2.volume OR 
density <> d2.density) 
) 

這將確保您獲得每個ID正確的最新的記錄,只有那些需要更新。

+0

CTE中的窗口函數也應該可以工作 – HLGEM

+0

花了我一段時間才弄清楚這個問題,但它運行良好 – Kilisi

0

UPDATE摘要SET重量= _weight,體積= _volume,密度= _density FROM ( SELECT ID _ID,重量_weight,體積_volume,密度_density FROM詳細 WHERE數IN(SELECT MAX(數)詳細GROUP BY ID) ) A WHERE ID = _ID