2011-12-13 89 views
2

值我有以下表作爲查詢的結果說calc_success_rateSQL查詢來插入列從行

server,  service,  timestamp,  success_rate 
123.23.23.2 ftp   1:00 am  1 
123.23.23.2 http   1:00 am  0.5 

我想插入這些值到另一個表說的指標,其結構如下

server  ftpSuccessRate  httpsuccessrate  timestamp 
123.23.23.2 1     0.5     1:00 

我會做calc_success_rate.servermetrics.servercalc_success_rate.timestampmetrics.timestamp之間的連接並插入ftpsuccessratehttpsuccessrate

是否有可能做到這一點在一個查詢

我需要一個更新語句是這樣的

update secondTable st 
set ftpSuccessRate = , httpSuccessRate = 
from firstTable ft 
where ft.server = st.server and ft.timestamp = st.timestamp 
+1

是否使用的是RDBMS? –

+1

我們使用Postgres 8.4 – user373201

回答

2
INSERT INTO SecondTable 
    (server, ftpSuccessRate, httpSuccessRate, timestamp) 
    SELECT server, 
      MAX(CASE WHEN service = 'ftp' THEN success_rate ELSE NULL END), 
      MAX(CASE WHEN service = 'http' THEN success_rate ELSE NULL END), 
      timestamp 
     FROM FirstTable 
     GROUP BY server, timestamp; 

編輯:根據評論,這裏的更新版本:

UPDATE st 
    SET ftpSuccessRate = q.ftpSuccessRate, 
     httpSuccessRate = q.httpSuccessRate 
    FROM (SELECT server, 
       MAX(CASE WHEN service = 'ftp' THEN success_rate ELSE NULL END) as ftpSuccessRate, 
       MAX(CASE WHEN service = 'http' THEN success_rate ELSE NULL END) as httpSuccessRate, 
       timestamp 
       FROM FirstTable 
       GROUP BY server, timestamp) q 
     INNER JOIN @SecondTable st 
      ON q.server = st.server 
       AND q.timestamp = st.timestamp 
+0

它更多的關於secondTable的更新聲明,並使用服務器和時間戳在它們之間進行連接。更新secondTable st set ftpSuccessRate =,httpSuccessRate = from firstTable ft其中ft.server = st.server和ft.timestamp = st.timestamp – user373201

+0

@ user373201:我將修改我的答案,但問題的主題明確指出「sql query to *插入*「 –

+0

抱歉。我的錯誤和感謝您的幫助 – user373201

1
INSERT INTO 
    youTable 
SELECT 
    server, 
    MAX(CASE WHEN service = 'ftp' THEN success_rate END) AS ftpSuccessRate, 
    MAX(CASE WHEN service = 'http' THEN success_rate END) AS httpSuccessRate, 
    timestamp 
FROM 
    yourOtherTable 
GROUP BY 
    server, 
    timestamp 


或作爲現有記錄的更新...

UPDATE 
    yourOtherTable 
SET 
    ftpSuccessRate = COALESCE(MAX(CASE WHEN service = 'ftp' THEN success_rate END), yourOtherTable.ftpSuccessRate), 
    httpSuccessRate = COALESCE(MAX(CASE WHEN service = 'http' THEN success_rate END), yourOtherTable.httpSuccessRate) 
FROM 
    yourOtherTable 
LEFT JOIN 
    yourtable 
    ON yourTable.server = yourOtherTable.server 
    AND yourTable.timestamp = yourOtherTable.timestamp 
GROUP BY 
    yourOtherTable.server 
    yourOtherTable.timestamp 
0
UPDATE 
    metrics SET 
     ftpSuccessRate = (CASE WHEN service = 'ftp' THEN success_rate ELSE NULL END), 
     httpsuccessrate = (CASE WHEN service = 'http' THEN success_rate ELSE NULL END)  
    FROM 
    calc_success_rate 
    WHERE 
    metrics.server = calc_success_rate.Server