2012-05-22 49 views
0
Table 1 - Deal ID, REF NOS, Type, Papa ID 

Table 2 - Deal ID, Type 

在新視圖中創建一個名爲Method的列。該領域的設置方式如下(4個條件);噩夢病例聲明援助pl

If Deal ID from table 1 Exists in Table 2 and Type is not Null from Table 2. 
Set Method used to be Y 

If Deal ID does not exist in Table 1 and Type does not contain 27,42 or 55 in Table 1. 
Set Method used to be Y 

If Papa ID is null from Table 1, and Type does not contain 27,42 or 55 in Table 1. 
Set Method used to be Y 

Else 

Set to N 

開始,並認爲哇!..

create view Master as ( 

select Deal ID, REF NOS, Type, Papa ID 

[Method used]= 
     Case 
      When 


from Table 1 A 
) 

回答

1

像這樣的東西可能工作(假設這些表上DealId加入)。請注意,我刪除了您在問題中顯示的一些列名稱中的空格。

鑑於這些表:

CREATE TABLE #Table1 (DealId INT, RefNos VARCHAR(100), [Type] VARCHAR(100), PapaId INT); 
CREATE TABLE #Table2 (DealId INT, [Type] VARCHAR(100)); 

查看示例:

WITH DealIds AS (
    SELECT DealId FROM #Table1 
    UNION 
    SELECT DealId FROM #Table2 
) 
SELECT 
CASE 
    -- If Deal ID from table 1 Exists in Table 2 and Type is not Null from Table 2. 
    -- Set Method used to be Y 
    WHEN t1.DealId IS NOT NULL AND t2.DealId IS NOT NULL AND t2.[Type] IS NOT NULL THEN 'Y' 

    -- If Deal ID does not exist in Table 1 and Type does not contain 27,42 or 55 in Table 1. 
    -- Set Method used to be Y 
    -- Note: it is is redundant to have the type condition if DealId is the PK. 
    WHEN t1.DealId IS NULL AND t1.[Type] NOT IN (27, 42, 55) THEN 'Y' 

    -- If Papa ID is null from Table 1, and Type does not contain 27,42 or 55 in Table 1. 
    -- Set Method used to be Y 
    WHEN t1.PapaId IS NULL AND t1.[Type] NOT IN (27,42, 55) THEN 'Y' 

    -- Else 
    -- Set to N 
    ELSE 'N' 
END AS MethodUsed 
FROM DealIds d 
LEFT JOIN #Table1 t1 ON d.DealId = t1.DealId 
LEFT JOIN #Table2 t2 ON d.DealId = t2.DealId 
+0

謝謝。這是一些很棒的SQL能力和理解所示! –