Почему `NOT IN` не работает, но подзапрос` NOT IN` работает? - PullRequest
1 голос
/ 20 апреля 2019

Я пытаюсь решить проблему Trips and Users SQL Leetcode . Если я правильно читаю, 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 Ответ

1 голос
/ 20 апреля 2019

Вам необходимо явно выбрать из CTE:

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 (select users_id from banned_usrs) and
    driver_id not in (select users_id from banned_usrs);
group by
    request_at;

Сам по себе CTE является просто кодом SQL и не образует подзапрос, если вы явно не напишите его как таковой.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...