我有下表作为查询结果说calc_success_rate
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.server
和metrics.server
以及calc_success_rate.timestamp
和metrics.timestamp
之间进行联接并插入ftpsuccessrate
和httpsuccessrate
是否可以在一个查询中执行此操作
我需要一个像这样的更新声明
update secondTable st
set ftpSuccessRate = , httpSuccessRate =
from firstTable ft
where ft.server = st.server and ft.timestamp = st.timestamp
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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