2012-04-20 48 views
0

我有一個臨時表(#WorkTable),它看起來像下面這樣:更新查表

InstrID CountryName CreditRating 
1  UK   AA 
2  UK   Unclassified 
3  South Africa A 
4  South Africa A 
5  South Africa Unclassified 

我希望能夠做的就是更新這個表,其中列企業資信爲「未分類」,其實際信用評級。所以在上面的例子中,英國未分類將成爲'AA',而南非將成爲'A'。

我不確定爲此編碼,任何幫助將不勝感激。

回答

0

下面的sql腳本會將任何未分​​類更新爲「實際」信用評級。我希望這有幫助。

CREATE TABLE #WorkTable 
(
    InstrID INT, 
    CountryName VARCHAR(50), 
    CreditRating VARCHAR(20) 
) 

INSERT INTO #WorkTable VALUES (1, 'UK','AA'); 
INSERT INTO #WorkTable VALUES (2, 'UK','Unclassified'); 
INSERT INTO #WorkTable VALUES (3, 'South Africa','A'); 
INSERT INTO #WorkTable VALUES (4, 'South Africa','A'); 
INSERT INTO #WorkTable VALUES (5, 'South Africa','Unclassified'); 

WITH cteUnclassified 
AS 

(
    SELECT InstrID, 
     CountryName, 
     CeditRating 

    FROM #WorkTable 
    WHERE CreditRating != 'Unclassified' 
) 


UPDATE #WorkTable 
SET CreditRating = u.CreditRating 
FROM #WorkTable wt 
    INNER JOIN cteUnclassified u 
ON wt.CountryName = u.CountryName 

WHERE wt.CreditRating = 'Unclassified' 

SELECT * 
FROM #WorkTable 

下面的查詢的結果:

InstrID國家或地區名稱企業資信 1 UK AA 2 UK AA 3南非甲 4南非甲 5南非甲

0

我想這個例子會幫助你。

String sql = "update table_name set CreditRating = (select unique CreditRating from table_name where CountryName = ? and CreditRating != 'classifie...') where CountryName = ? and CreditRating = 'classifie...'"; 

在這裏,您可以將countryName作爲paramaeter傳遞。

0

你似乎對SQL很陌生。你需要做的是將表「加入」查詢值。你可以在很多地方找到很多有關SQL基礎知識的幫助,但是如果你需要一個快速解決方案,請嘗試以下內容:

如果你有一個與國家和信用評級分開的表,(我假定了名字那表是評級,以及國名和等級相匹配。)

update #WorkTable 
    Set w.Creditrating = r.CreditRating 
    from #WorkTable w join Rating r on w.CountryName=r.CountryName 
    where w.CreditRating='Unclassified' 

在另一方面,如果沒有單獨的表中存在,並希望基於相同的臨時表更新非保密值,那麼你需要假設表中已經有一些對於該國家的信用評級(這在你發佈的情況下是有的)。它還需要每個國家只有一個CreditRating。在這種情況下,下面應該工作:

update #WorkTable 
    Set w.Creditrating = w2.CreditRating 
    from #WorkTable w join 
    (Select distinct CountryName, CreditRating from #WorkTable where CreditRating<>'Unclassified') w2 
     on w.CountryName=w2.CountryName 
    where w.CreditRating='Unclassified' 

這將使用表本身找到價值,通過在表中查找兩次 - 一次作爲表進行更新,在最後一行限制什麼更新爲只未分類的項目,並且一次作爲源表格,其中僅使用分類評級。如果這對你不起作用,請留下更多詳情的評論。