2011-12-29 82 views
0

下面我試圖從子表更新父表的值和計數匹配值。我的數據庫中的表格:子表中的更新,只有一個值得到更新

  1. issue_dimension id = issue_id並具有列accno。

  2. star_schema id爲star_id,這個孩子柱已FK ISSUE_ID和列book_frequency

的book_frequency需要匹配在父表中每個登錄號的數量,我想這

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 
) 

它僅更新第一個值計數issue_dimension。我需要計算issue_dimension中的每個accno並將其更新爲匹配star_schema的accno。

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 
     ) 

回答

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) 

我不」: 我從來沒有通過連接兩個或多個表,任何人都可以在此幫助加入這樣

+0

它再次只更新一個值,它只計算一個值 – user1074474 2011-12-29 07:52:07

+0

有多少行返回:'SELECT ACCNO,COUNT(*)as CNT FROM issue_dimension GROUP BY ACC_NO HAVING COUNT(*)> 1'? – chopikadze 2011-12-29 08:35:27

0

嘗試,不進行分組,只是用WHERE條款做了更新牛逼檢查它,但它應該工作

+0

嗯,依然的擊打更新一個結果 – user1074474 2011-12-29 07:11:20

+0

將其與連接解決?我從來沒有在更新語句中使用連接 – user1074474 2011-12-29 07:12:06

+1

您可以在更新中使用連接,但我認爲不是GROUP BY,那麼,可能是您再次剝離HAVING COUNT(*)> 1? – 2011-12-29 07:20:53

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 
+0

這裏是不必要的加入issue_dimension :) – chopikadze 2011-12-29 07:22:40

+0

@chopikadze:在問題中,完全部分描述表沒有關於表'star_schema'中列'accno'的信息。我注意到的唯一連接是'issue_dimension.issue_id(id,可能是PK)= star_schema.issue_id(FK)'。這就是我用它來加入它們的原因。 – 2011-12-29 07:31:03

+0

但問題中的示例查詢包含:)好吧,無論如何,我們的答案都非常接近,應該允許提問者找到正確的解決方案,我認爲:) – chopikadze 2011-12-29 07:34:12

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);