梦魇案例陈述援助pl

时间:2012-05-22 18:29:37

标签: sql

Table 1 - Deal ID, REF NOS, Type, Papa ID

Table 2 - Deal ID, Type

在名为Method的新视图中创建列。该字段的设置方式如下(4个条件);

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 个答案:

答案 0 :(得分: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