sql函数case返回多行

时间:2017-02-21 13:47:52

标签: sql oracle

要将此查询用作子查询,问题是它返回多行重复项。尝试使用COUNT()而不是exists,但它仍然返回多个答案。    每个表只能包含一个superRef记录。

以下查询我将在SELECT col_a,[CASE] From MyTable

中使用
<appSettings>
   <add key="owin:AutomaticAppStartup" value="false" />   
</appSettings>

结果:

SELECT CASE
        WHEN 
         EXISTS (SELECT 1 FROM A WHERE 
            A_superRef = myTable.sysno AND A_specAttr = 'value')
        THEN 3
        WHEN     EXISTS (SELECT 1 FROM B 
            INNER JOIN С ON С_ReferenceForB = B_sysNo WHERE C_superRef = myTable.sysno AND b_type = 2)
        THEN 2
        ELSE (SELECT C_intType FROM C 
            WHERE C_superRef = myTable.sysno)
        END
    FROM A, B, C

2 个答案:

答案 0 :(得分:1)

如果你这样做怎么办?因为我猜你正在获得一个隐式的全外连接A X B X C,然后为该结果集中的每一行运行case语句。

SELECT CASE
    WHEN 
     EXISTS (SELECT 1 FROM A WHERE 
        A_superRef = 1000001838012)
    THEN 3
    WHEN     EXISTS (SELECT 1 FROM B 
        INNER JOIN С ON С_ReferenceForB = B_sysNo AND C_superRef = 1000001838012 )
    THEN 2
    ELSE (SELECT C_type FROM C 
        WHERE C_superRef = 1000001838012)
    END
FROM ( SELECT COUNT(*) FROM A ) --This is a hack but should work in ANSI sql.
                                --Your milage my vary with different RDBMS flavors. 

答案 1 :(得分:0)

DUAL是我需要的,感谢Thorsten Kettner

SELECT CASE
    WHEN 
     EXISTS (SELECT 1 FROM A WHERE 
        A_superRef = 1000001838012)
    THEN 3
    WHEN     EXISTS (SELECT 1 FROM B 
        INNER JOIN С ON С_ReferenceForB = B_sysNo AND C_superRef = 1000001838012 )
    THEN 2
    ELSE (SELECT C_type FROM C 
        WHERE C_superRef = 1000001838012)
    END
FROM DUAL