我有两张桌子
1.Project_Cust_Packages__c
Project_Id__c | LOV_Name__c |
101 | PAS |
101 | PMS |
101 | FTR |
2.AAProj_Tbl
ID | ISPAS |ISPMS |ISFTR |
101 | NULL | NULL | NULL |
UPDATE AAProj_Tbl
SET ISPAS=
CASE
WHEN A.[LOV_Name__c]='PAS' THEN 'Y'
WHEN ISPAS='Y' THEN 'Y'
ELSE 'N'
END
,ISPMS=
CASE
WHEN A.[LOV_Name__c]='PMS' THEN 'Y'
WHEN ISPMS='Y' THEN 'Y'
ELSE 'N'
END
,ISFTR=
CASE
WHEN A.[LOV_Name__c]='FTR' THEN 'Y'
WHEN ISFTR='Y' THEN 'Y'
ELSE 'N'
END
FROM [Project_Cust_Packages__c] A inner join AAProj_Tbl B
on B.ID=A.[Project_Id__c]
结果是
AAProj_Tbl
ID | ISPAS |ISPMS |ISFTR |
101 | N | N | Y |
但结果应为
ID | ISPAS |ISPMS |ISFTR |
101 | Y | Y | Y |
所有列中的Y,Y,Y因为: Project_Cust_Package_c表有包含FTR,PMS,FTR ......的项目。
答案 0 :(得分:5)
在构建这样的查询时(即从多行更新单行中的多个列),您需要确保将两个表转换为一对一关系。这样做的一种方法是转动表A,如下所示:
UPDATE AAProj_Tbl
SET ISPAS=
CASE
WHEN A.[PAS] > 0 THEN 'Y'
ELSE 'N'
END
,ISPMS=
CASE
WHEN A.[PMS] > 0 THEN 'Y'
ELSE 'N'
END
,ISFTR=
CASE
WHEN A.[FTR] > 0 THEN 'Y'
ELSE 'N'
END
FROM
(SELECT [Project_Id__c],
SUM(CASE WHEN [LOV_Name__c] = 'PAS' THEN 1 ELSE 0 END) AS [PAS],
SUM(CASE WHEN [LOV_Name__c] = 'PMS' THEN 1 ELSE 0 END) AS [PMS],
SUM(CASE WHEN [LOV_Name__c] = 'FTR' THEN 1 ELSE 0 END) AS [FTR],
FROM [Project_Cust_Packages__c] GROUP BY [Project_Id__c]) AS A
inner join AAProj_Tbl B
on B.ID=A.[Project_Id__c]