使用CASE&合并

时间:2015-07-01 12:48:15

标签: sql-server-2008 case coalesce

这种语法只给我一个无用的错误

  

mentorname附近的语法不正确

如何更新以强制显示结果?

SELECT COALESCE(case when
            mentorname LIKE '%Med%' THEN 'MedTronics' end
            mentorname LIKE '%Zi%' THEN 'Zinamice' end
            , 'Total') As [Prov Source]

来自database1

2 个答案:

答案 0 :(得分:5)

试试这个:

SELECT COALESCE(CASE 
                    WHEN mentorname LIKE '%Med%' 
                        THEN 'MedTronics'
                    WHEN mentorname LIKE '%Zi%' 
                        THEN 'Zinamice' 
               END
            , 'Total') As [Prov Source]

虽然您可以简化查询并完全删除COALESCE,但只留下CASE

SELECT
    CASE 
        WHEN mentorname LIKE '%Med%'
            THEN 'MedTronics'
        WHEN mentorname LIKE '%Zi%'
            THEN 'Zinamice'
        ELSE 'Total'
    END AS [Prov Source]

答案 1 :(得分:1)

为了简单起见,您可以使用嵌套的CASE语句完成相同的操作,并完全避免COALESCE ...

SELECT 
    [Prov Source] = 
        CASE WHEN mentorname LIKE '%Med%' THEN 
            'MedTronics' 
        ELSE
            CASE WHEN mentorname LIKE '%Zi%' THEN 
                'Zinamice' 
            ELSE
                'Total'
            END
        END