如何在SELECT中使用CASE?

时间:2017-07-14 11:00:03

标签: sql sql-server select subquery case

我正在使用SQL Server。整个查询要长得多,我希望专注于需要修复的部分。我有这样的东西有效:

SELECT 
    a, b, ..., g, 
    (SELECT p.name + ' (' + pd.class + ')' 
     FROM person p 
     INNER JOIN person_data pd ON p.personid = pd.personid AND pd.typeid = 1 
     WHERE p.personid = k.contactid) as Person
FROM 
    maindata md
INNER JOIN 
    ........

我想将pd.class替换为CASE语句,如

CASE (SELECT ....)
    WHEN 1 THEN ....
    WHEN 2 THEN ....
END

我在查询中使用了这样的CASE语句,但它们已分别在原始SELECT中(参见a,b等)。如何在CASE内的SELECT中插入SELECT语句?

类似的东西:

SELECT 
    a, b, ..., g, 
    (SELECT p.name + ' (' + 
        class = (CASE (SELECT .....)
            WHEN 1 THEN ....
            WHEN 2 THEN ....
        END)
     + ')' FROM person p 
    INNER JOIN person_data pd ON p.personid = pd.personid AND pd.typeid = 1 
    WHERE p.personid = k.contactid) as Person
FROM maindata md
INNER JOIN ........

0 个答案:

没有答案