使用 SQL 服务器,我如何根据子查询更新所有行,但每一行都不同
With SQL Server, how can I update all rows but each one differently based on subquery
这是一个例子table:
BookID PK int
Book varchar(50)
Author varchar(50)
Sales int
我想一次更新所有销售计数,但基于子查询。
UPDATE BookTable SET Sales = (
-- Mixture of T-SQL and pseudo code
SELECT COUNT(SaleID) FROM BookSalesTable
WHERE LiveMode = 1
AND BookID = for each...
)
这样你就可以看到我的挂断了。我以前做过这个,只是为了我的生活不记得是怎么做的。我宁愿不创建临时 table 因为我很确定它在更新中处理得很好。所以我需要根据每个 BookID 更新所有行的计数,因为每一行都会不同。这可以不用循环来完成吗?
我上面评论的一个例子:
UPDATE bt
SET Sales = (
SELECT COUNT(SaleID) FROM BookSalesTable bst
WHERE bst.LiveMode = 1
AND bst.BookID = bt.BookID
)
FROM BookTable bt
UPDATE B
SET B.Sales = BS.Sales
FROM BookTable B INNER JOIN
(SELECT BookID , COUNT(*) AS Sales
FROM BookSalesTable
WHERE LiveMode = 1
GROUP BY BookID )BS
ON B.BookID = BS.BookID
这是一个例子table:
BookID PK int
Book varchar(50)
Author varchar(50)
Sales int
我想一次更新所有销售计数,但基于子查询。
UPDATE BookTable SET Sales = (
-- Mixture of T-SQL and pseudo code
SELECT COUNT(SaleID) FROM BookSalesTable
WHERE LiveMode = 1
AND BookID = for each...
)
这样你就可以看到我的挂断了。我以前做过这个,只是为了我的生活不记得是怎么做的。我宁愿不创建临时 table 因为我很确定它在更新中处理得很好。所以我需要根据每个 BookID 更新所有行的计数,因为每一行都会不同。这可以不用循环来完成吗?
我上面评论的一个例子:
UPDATE bt
SET Sales = (
SELECT COUNT(SaleID) FROM BookSalesTable bst
WHERE bst.LiveMode = 1
AND bst.BookID = bt.BookID
)
FROM BookTable bt
UPDATE B
SET B.Sales = BS.Sales
FROM BookTable B INNER JOIN
(SELECT BookID , COUNT(*) AS Sales
FROM BookSalesTable
WHERE LiveMode = 1
GROUP BY BookID )BS
ON B.BookID = BS.BookID