我想检查客户是否有特定产品。如果他们这样做,请返回是。如果他们不这样做,请返回否。
所以,我写了一个返回它的查询。但是,我不想输入ProductFamily
名称。我想要加入。
SELECT
ID,
(CASE
WHEN ProductFamily IN ('Product')
THEN 'Yes'
ELSE 'No'
END) AS 'O'
FROM
[source].[Opportunity] A
以下查询让我知道ProductFamily
映射:
SELECT *
FROM [reference].[ProductFamilyMapping]
WHERE (isA = 1)
ORDER BY productfamilyname
如何加入案例陈述?
答案 0 :(得分:1)
您可以在IN语句中放置子查询而不是硬编码文本,但您需要指定列名称(即“SELECT mycolumn”而不是“SELECT *”)。
SELECT
ID
,(CASE
WHEN ProductFamily IN
(SELECT ProductFamily FROM [reference].[ProductFamilyMapping] where (isA = 1))
THEN 'Yes'
ELSE 'No' END) as 'O'
From [source].[Opportunity] A
(我假设[reference]中的列名。[ProductFamilyMapping]也是ProductFamily)。
答案 1 :(得分:1)
另一种选择可能是使用CTE和LEFT JOIN。 试试这个:
WITH PFM AS (
SELECT DISTINCT ProductFamily FROM [reference].[ProductFamilyMapping] where (isA = 1)
)
SELECT
ID
,CASE WHEN PFM.ProductFamily IS NULL THEN 'No' ELSE 'Yes' END AS 'O'
From [source].[Opportunity] A
LEFT JOIN PFM ON A.ProductFamily = PFM.ProductFamily