仅当所有列都存在时才更新 - SQL Server 2008

时间:2016-08-18 02:38:00

标签: sql sql-server-2008

我有Animal表的下面提到的表结构:

AnimalId | AnimalName | SelectAnimal
1        | Cat        | NULL
2        | Dog        | NULL
3        | Sheep      | NULL
4        | Cow        | NULL

AnimalFeature表:

Animal Id | Feature | Present 
1         | Teeth   | Y      
1         | Milk    | Y
1         | Tail    | Y
2         | Teeth   | Y
3         | MILK    | Y
4         | Teeth   | Y
4         | MILK    | N
4         | Tail    | Y

我正在使用以下查询为当前列生成逗号分隔列表

SELECT DISTINCT
    A1.AnimalId,
    STUFF((SELECT ', ' + ltrim(rtrim(A2.Present))
           FROM Animal AS A2
           WHERE A1.AnimalId = A2.AnimalId
           FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '') As ConcatValue 
FROM    
    Animal as A1 
GROUP BY 
    AnimalId;

要求是仅在存在所有特征时才更新动物主表。

如果前两个功能为是,则selectanimal列将为是,否则为否 如果不是所有功能都存在,则需要忽略这些记录。

最终输出应该是

1   CAT    Y 
2   DOG    NULL
3   SHEEP  NULL 
4   COW    N    

您能否提供有关如何完成此任务的任何指示或帮助?

1 个答案:

答案 0 :(得分:1)

以下内容应该做你需要的事情

WITH AF AS (
SELECT AnimalId,
       CASE WHEN COUNT(DISTINCT CASE 
                                 WHEN Present = 'Y' AND Feature IN ('Teeth', 'Milk' 
                                 THEN Feature 
                                 END) >= 2 
            THEN 'Y' 
            ELSE 'N' 
            END AS SelectAnimal         
FROM AnimalFeature
WHERE Feature IN ('Teeth', 'Milk', 'Tail')
GROUP BY AnimalId
HAVING COUNT(DISTINCT Feature) = 3
)
UPDATE A
SET A.SelectAnimal = AF.SelectAnimal
FROM Animal A JOIN AF ON A.AnimalId = AF.AnimalId