在SELECT中使用布尔子查询

时间:2015-06-01 14:20:09

标签: sql-server

SELECT A.ID AS Asta
    ,B.GPS.Lat AS Lng
    ,B.GPS.Long AS Lat
    ,B.Tipo AS Tipo
    ,B.Via AS Via
    ,A.Stato AS Stato
    ,(
        SELECT COUNT(*)
        FROM SIBA_Vendite
        WHERE Lotto = B.Lotto
            AND Data > GETDATE()
        ) AS Attiva
    ,(
        SELECT TOP (1) Esito
        FROM SIBA_Vendite
        WHERE Lotto = B.Lotto
        ORDER BY Data
        ) = (
        SELECT ID
        FROM SIBA_Esiti
        WHERE NAME = 'DESERTA'
        ) AS Deserta
FROM SIBA_Beni B
INNER JOIN SIBA_Aste A ON B.Asta = A.ID

正在返回

Messaggio 102, livello 15, stato 1, riga 1
Incorrect syntax near '='.
Messaggio 156, livello 15, stato 1, riga 1
Incorrect syntax near the keyword 'AS'.

错误的部分是两个子查询之间的=。我试图获得= as" Deserta"的布尔结果。字段

1 个答案:

答案 0 :(得分:1)

SQL Server没有布尔数据类型,因此您别无选择,只能使用caseiif表达式来处理这种情况。 e.g。

Deserta =case when (SELECT TOP (1) Esito
        FROM SIBA_Vendite
        WHERE Lotto = B.Lotto
        ORDER BY Data) = (
        SELECT ID
        FROM SIBA_Esiti
        WHERE NAME = 'DESERTA'
        ) then 1 else 0 end