1

我有一个主表,其中包含每个子表的所有 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表中有两个字段,分别称为NormalTypeSupertype。如果其中任何一个字段有值,我需要将其显示在名为Type的列中。但是,如果两者都没有值,我需要在类型列中显示一个空白值。有任何想法吗?

- -编辑

我在编辑后的查询中放置的 COALESCE 是否正确?它仍然返回错误。

- 更新

重要提示:两个字段的类型都是布尔值,我需要返回包含 TRUE 值的列的列名,并将该值放在 TYPE 列中。

4

2 回答 2

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
于 2012-10-27T21:24:37.533 回答
1

看到您的评论,也许一个CASE表达式会起作用:

select ...
      , CASE WHEN ComponentRuleSet.NormalType is not null then 'NormalType'
             WHEN ComponentRuleSet.Supertype  is not null then 'SuperType'
             ELSE ''
             end as Type

更新由于布尔值只有 1 代表真,0 代表假,试试这个:

select ...
      , CASE WHEN ComponentRuleSet.NormalType = 1 then 'NormalType'
             WHEN ComponentRuleSet.Supertype  = 1 then 'SuperType'
             ELSE ''
             end as Type
于 2012-10-27T22:05:56.657 回答