我有查询要从相关表中选择数据。
SELECT
s.id,
CASE
WHEN count(DISTINCT e.id) <> 0
THEN count(DISTINCT o.id) / count(DISTINCT e.id)
END OrdersAverageNumber
FROM
[School] s
JOIN
[SchoolStore] ss ON ss.SchoolId = s.Id
JOIN
[Event] e ON e.SchoolId = ss.SchoolId
AND e.IsDeleted = 0
AND e.Status = 1
AND e.Date >= @startDate
AND e.Date <= @endDate
JOIN
[Order] o ON o.EventId = e.id
AND o.OrderStatus = 1
AND o.CreatedDate >= @startDate
AND o.CreatedDate <= @endDate
GROUP BY
s.id;
但是我不知道我需要更改以使用上面选择的值更新OrdersAverageNumber
表中的所有 School
条记录。
答案 0 :(得分:3)
您可以使用update
:
with q as (< your query here >)
update s
set OrdersAverageNumber = q.OrdersAverageNumber
from school s join
q
on s.id = q.id;