我有一个主表,其中包含每个子表的所有ID。 SQL语句看起来像这样......
SELECT Class.Descript
, Regulation.Descript AS Reg
, Compgroup.Descript AS Grouping
, Category.Descript AS Cat
, Exempt.Descript AS Exempt
, Reason.Descript AS Reasons
, COALESCE(ComponentRuleSet.NormalType, ComponentRuleSet.Supertype, '') AS Type
FROM ComponentRuleSet
LEFT OUTER JOIN Reason
ON ComponentRuleSet.ComponentCategoryID = Reason.ComponentCategoryID
LEFT OUTER JOIN Class
ON ComponentRuleSet.ComponentClassID = Class.ComponentClassID
LEFT OUTER JOIN Regulation
ON ComponentRuleSet.RegulationID = Regulation.RegulationID
LEFT OUTER JOIN Compgroup
ON ComponentRuleSet.ComplianceGroupID = Compgroup.ComplianceGroupID
LEFT OUTER JOIN Category
ON ComponentRuleSet.ComponentCategoryID = Category.ComponentCategoryId
LEFT OUTER JOIN Exempt
ON ComponentRuleSet.ExemptID = Exempt.ComponentExemptionID
WHERE (ComponentRuleSet.ComponentID = 38048)
问题是 ComponentRuleSet 表中有两个字段,名为 NormalType 和超类型。如果其中任何一个字段都有值,我需要在名为类型的列中显示它。然而,如果两者都没有值,我需要在类型列中显示空白值。 有什么想法吗?
--- EDIT
我在编辑的查询中的COALESCE位置是否正确?它仍然会返回错误。
- UPDATE
重要说明:两个字段的类型都是布尔值,我需要返回包含TRUE值的列的列名,并将该值放在TYPE列中。
答案 0 :(得分:3)
对此字段使用COALESCE
:
COALESCE(ComponentRuleSet.NormalType, ComponentRuleSet.Supertype, '') AS Type
COALESCE
:
返回其参数中的第一个非空表达式。
根据您对实际要求的评论,CASE
可能是更好的选择:
CASE WHEN ComponentRuleSet.NormalType = 1 THEN 'NormalType'
WHEN ComponentRuleSet.Supertype = 1 THEN 'SuperType'
ELSE ''
END AS Type
答案 1 :(得分:1)
看到你的评论,也许CASE
表达式可以起作用:
select ...
, CASE WHEN ComponentRuleSet.NormalType is not null then 'NormalType'
WHEN ComponentRuleSet.Supertype is not null then 'SuperType'
ELSE ''
end as Type
UPDATE 由于布尔值对于true只有1而对于false为0,请尝试:
select ...
, CASE WHEN ComponentRuleSet.NormalType = 1 then 'NormalType'
WHEN ComponentRuleSet.Supertype = 1 then 'SuperType'
ELSE ''
end as Type