2016-12-06 170 views
0

我有以下表格。基於另一個表中的列值的更新表

表1

Id | Data | Values 
1 | rfsd | 23 
2 | fghf | 45 
3 | rhhh | 23 

表3

Id | Data | Values 
1 | rfsd | 23 
2 | tfgy | 23 

表2

Id | Fields | Counts 
1 | 23  | 0 
2 | 45  | 0 

正如你可以看到,計數字段的值爲0我想看 '字段' 列在表2中,然後與表1和表3中的'值'列進行比較,並在'值'字段中存在該值時增加計數。

最終的結果應該顯示像這樣

Table 2 
Id | Fields | Counts 
1 | 23  | 4 
2 | 45  | 1 

這將是數自23出現四次,45在「價值」表1和表的字段出現一次3.

燦有人請讓我知道如何爲此編寫存儲過程。

我已經實現了這樣的東西。

WITH t1 AS (
       SELECT VALUES, COUNT(*) AS Count2 FROM Table1 GROUP BY VALUES) 
UPDATE t2 
SET t2.Counts = t1.Count2 
FROM Table2 t2 
JOIN t1 ON t2.Fields=t1.Values; 

WITH t3 AS (SELECT VALUES, COUNT(*) AS Count3 FROM Table3 GROUP BY VALUES) 
UPDATE t2 
SET t2.Counts = t3.Count2 
FROM 
Table2 t2 
JOIN t3 ON t2.Fields=t3.Values; 

當我使用這個存儲過程時,它將基於t1表更新t2,然後使用t3表覆蓋表t2。

我希望t1和t3列在t2表上同時更新。任何想法如何糾正這個存儲過程。

回答

1

您可以使用UNION ALL到組兩個表1和3一起(UNION ALL如果你想不交,UNION如果你想刪除重複的)

WITH t13 AS (
    SELECT Id, Data, [Values] 
    FROM Table1 
    UNION ALL 
    SELECT Id, Data, [Values] 
    FROM Table3 
), cte AS (
    SELECT 
     [Values], 
     COUNT(*) AS Count2 
    FROM t13 
    GROUP BY 
     [Values] 
) 
UPDATE t2 
SET Counts = cte.Count2 
FROM 
    Table2 t2 JOIN cte ON t2.Fields = cte.[Values]; 
+0

它說,由多個部分組成的標識符「cte.Count2」無法綁定。任何我誤會? –

+1

@AduRao固定。 UPDATE中JOIN中的表應該是cte而不是t13。 – DVT

+1

@AduRao我不認爲這是要求upvote的正確方法。 http://meta.stackoverflow.com/questions/255583/what-c​​an-i-do-when-getting-we-are-no-longer-accepting-questions-answers-from-th – DVT

1

希望這會有所幫助。

SELECT t2.Id, t2.Fields, COUNT(1) Counts 
FROM Table2 t2 
    LEFT JOIN Table1 t1 ON t2.Fields = t1.[Values] 
    LEFT JOIN Table3 t3 ON t2.Fields = t3.[Values] 
GROUP BY t2.Id, t2.Fields 

如果您需要更新表2,使用以下命令: -

WITH Results AS (
    SELECT t2.Id, COUNT(1) Counts 
    FROM Table2 t2 
     LEFT JOIN Table1 t1 ON t2.Fields = t1.[Values] 
     LEFT JOIN Table3 t3 ON t2.Fields = t3.[Values] 
    GROUP BY t2.Id 
) 
UPDATE t 
SET Counts = r.Counts 
FROM Table2 t 
    JOIN Results r ON t.Id = r.Id; 
相關問題