如何使用sql update
语句中的聚合函数更新表的列?
答案 0 :(得分:6)
根据定义,聚合函数将输入的一个或多个记录聚合到结果集中的单个记录中,因此您想要更新哪个记录并不明显。
通常,您可以在子查询中使用聚合函数:
UPDATE mytable
SET mycol =
(
SELECT SUM(othercol)
FROM othertable o
WHERE o.yetothercol = m.yetmycol
)
,在JOIN
中(适用于MySQL
和SQL Server
)
UPDATE mytable
JOIN (
SELECT yetothercol, SUM(othercol) AS psum
FROM othertable
GROUP BY
yetothercol
) s
ON yetmycol = yetothercol
SET mycol = psum
或MERGE
语句(适用于Oracle
和SQL Server 2008
):
MERGE
INTO mycol
USING (
SELECT yetothercol, SUM(othercol) AS psum
FROM othertable
GROUP BY
yetothercol
) s
ON (yetmycol = yetothercol)
WHEN MATCHED THEN
UPDATE
SET mycol = psum