下面我试图从子表更新父表的值并计算匹配值。我的数据库中的表:
issue_dimension
,ID = issue_id,并且列为accno。
star_schema
,此子列有fk issue_id和列book_frequency
book_frequency需要匹配父表中每个accno的计数,我试过这个
update [test1] .[dbo] .star_schema
set [book_frequency] = (
select top 1 COUNT([issue_dimension].ACCNO)as book_frequency
from issue_dimension
group by ACCNO having (COUNT(*)>1) and
issue_dimension.ACCNO = star_schema .ACCNO
)
它仅更新第一个值count_dimension。我需要计算issue_dimension中的每个accno并将其更新为star_schema的匹配accno。 我从来没有通过加入两个或更多表来进行更新,任何人都可以通过加入帮助
答案 0 :(得分:1)
UPDATE s
SET [book_frequency] = i.CNT
FROM [test1].[dbo].star_schema s
INNER JOIN
(
SELECT ACCNO, COUNT(*) as CNT
FROM issue_dimension
GROUP BY ACC_NO
HAVING COUNT(*)>1
) i on (s.ACCNO = i.ACCNO)
我没有检查它但它应该有效
答案 1 :(得分:0)
尝试这种方式,无需分组,只需使用WHERE
子句:
UPDATE [test1].[dbo].star_schema SET
[book_frequency] =
(
SELECT COUNT([issue_dimension].ACCNO)
FROM issue_dimension
WHERE issue_dimension .ACCNO = star_schema.ACCNO
HAVING COUNT(*)>1
)
答案 2 :(得分:0)
我还不完全清楚,所以答案有点猜测:
update s set
book_frequency = t.qty
from star_schema s
join issue_dimension i on s.issue_id = s.issue_id
join (select count(*) as qty, accno
from issue_dimension
group by accno
) t on i.accno = t.accno
答案 3 :(得分:0)
以下是BOL的例子,使用AW来做你正在寻找的事情:
USE AdventureWorks2008R2;
GO
UPDATE Sales.SalesPerson
SET SalesYTD = SalesYTD +
(SELECT SUM(so.SubTotal)
FROM Sales.SalesOrderHeader AS so
WHERE so.OrderDate = (SELECT MAX(OrderDate)
FROM Sales.SalesOrderHeader AS so2
WHERE so2.SalesPersonID = so.SalesPersonID)
AND Sales.SalesPerson.BusinessEntityID = so.SalesPersonID
GROUP BY so.SalesPersonID);