MS SQL:检查多个条件,并在select语句中将组合结果作为字段返回

时间:2019-03-28 10:57:08

标签: sql-server

我正在实现MS SQL查询,在该查询中,我需要检查所有条件并在一个字段(OupputField)中获取合并结果作为字符串。

表格:客户

Id  Customer Type Active
------------------------
1   John     1    1     
2   Bob      2    0     
3   TOM      0    1     

我试图通过检查 ALL 不同情况来获取 OupputField 值。但它会检查一个真实条件并返回结果。我需要检查所有情况,并需要返回合并结果作为OutputField

预期输出:

Id  Customer Type Active OutputField
--------------------------------------
1   John     1    1      Type1, Active
2   Bob      2    0      Type2
3   TOM      0    1      Active

MS SQL查询:

select 
    Id,
    Customer,
    TypeId
    Active
    COALESCE
    (
     CASE 
        WHEN  TypeId = 1 
        THEN  'Type1'
     END,
     CASE 
        WHEN  Active = 1 
        THEN  'Active'
     END
    )
from Customer

我做错什么了吗?请帮助我。

谢谢。

2 个答案:

答案 0 :(得分:0)

select case when type = 0 and active = 0 then ''
            when type = 0 and active = 1 then 'Active'
            when type > 0 and active = 0 then 'Type' + cast(type as varchar)
            when type > 0 and active = 1 then 'Type' + cast(type as varchar) + ', Active'
       end as result
from your_table

答案 1 :(得分:0)

CREATE TABLE #tmp(Id int, Customer varchar(20), TypeId int, Active int)
INSERT INTO #tmp (Id,Customer,TypeId,Active) VALUES(1,'John',1,1)
INSERT INTO #tmp (Id,Customer,TypeId,Active) VALUES(2,'Bob',2,0)
INSERT INTO #tmp (Id,Customer,TypeId,Active) VALUES(3,'TOM',0,1)
INSERT INTO #tmp (Id,Customer,TypeId,Active) VALUES(4,'Jim',0,0)

select Id,    Customer,
    TypeId
    Active,
    CASE WHEN TypeID >0 THEN 'TypeId' + CAST(TypeID as varchar(3)) ELSE '' END +
        CASE WHEN TypeID > 0 AND Active > 0 THEN ', ' ELSE '' END + 
            CASE WHEN Active > 0 THEN 'Active'  ELSE '' END OutputField
from #tmp