更新现有SELECT查询中的所有记录

时间:2019-05-17 10:22:25

标签: sql sql-server

我有查询要从相关表中选择数据。

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条记录。

1 个答案:

答案 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;