为什么`NOT IN` cte不起作用而`NOT IN`子查询起作用?

时间:2019-04-20 01:40:27

标签: sql sql-server

我正在尝试解决Trips and Users SQL Leetcode problem。如果我没看错,NOT IN cte不起作用,但是NOT IN子查询起作用。为什么?

以下代码有效。

select request_at as Day, 
        cast(sum(iif(status like 'cancelled%', 1.0, 0.0))/count(status) as decimal(4,2)) as [Cancellation Rate]
from trips 
where (request_at between '2013-10-01' and '2013-10-03')
        and client_id not in (SELECT USERS_ID FROM USERS WHERE BANNED='Yes')
        and driver_id not in (SELECT USERS_ID FROM USERS WHERE BANNED='Yes')
group by request_at

但是下面的一个没有。我收到错误消息:

Runtime Error
[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Incorrect syntax near 'BANNED_USRS'. (102) (SQLExecDirectW)
with 
banned_usrs as 
(select users_id from users where banned = 'Yes')

select request_at as Day, 
        cast(sum(iif(status like 'cancelled%', 1.0, 0.0))/count(status) as decimal(4,2)) as [Cancellation Rate]
from trips 
where (request_at between '2013-10-01' and '2013-10-03')
        and client_id not in banned_usrs
        and driver_id not in banned_usrs
group by request_at

1 个答案:

答案 0 :(得分:1)

您需要从CTE中明确选择:

do_something(result[0][i], result[0][i])

CTE本身就是SQL代码,除非您明确地这样编写,否则不会构成子查询。