如何在 NOT IN 子句中使用来自 select 语句的字符串列表
How can I use a string list from a select statement in a NOT IN clause
我想建立一个姓氏列表,以便从第二个 select 语句的结果中过滤掉类似这样的东西(没有这样做)
DECLARE @ExcludedList VARCHAR(MAX)
SET @ExcludedList = (SELECT TOP 20 Lastname
FROM dbo.Subscribers
where [Firstname] = 'Dave')
SELECT [Firstname], Count([Firstname]) as [Count] from Subscribers
WHERE [Lastname] not in (@ExcludedList)
为什么不能像
那样直接做
SELECT [Firstname], Count([Firstname]) as [Count] from Subscribers
WHERE [Lastname] not in (SELECT TOP 20 Lastname
FROM dbo.Subscribers where [Firstname] = 'Dave')
嗯,我不确定你到底想达到什么目的,但考虑使用 table variable
并像下面那样使用
DECLARE @ExcludedList table(lastname varchar(30));
insert into @ExcludedList
SELECT TOP 20 Lastname
FROM dbo.Subscribers where [Firstname] = 'Dave';
SELECT [Firstname], Count([Firstname]) as [Count] from Subscribers
WHERE [Lastname] not in (select lastname from @ExcludedList);
如果需要使用变量,则必须是table变量:
DECLARE @ExcludedList TABLE (Lastname VARCHAR(MAX))
INSERT INTO @ExcludedList
SELECT TOP 20 Lastname
FROM dbo.Subscribers
WHERE [Firstname] = 'Dave'
SELECT [Firstname], Count([Firstname]) AS [Count]
FROM Subscribers
WHERE [Lastname] NOT IN (SELECT Lastname FROM @ExcludedList)
我想建立一个姓氏列表,以便从第二个 select 语句的结果中过滤掉类似这样的东西(没有这样做)
DECLARE @ExcludedList VARCHAR(MAX)
SET @ExcludedList = (SELECT TOP 20 Lastname
FROM dbo.Subscribers
where [Firstname] = 'Dave')
SELECT [Firstname], Count([Firstname]) as [Count] from Subscribers
WHERE [Lastname] not in (@ExcludedList)
为什么不能像
那样直接做SELECT [Firstname], Count([Firstname]) as [Count] from Subscribers
WHERE [Lastname] not in (SELECT TOP 20 Lastname
FROM dbo.Subscribers where [Firstname] = 'Dave')
嗯,我不确定你到底想达到什么目的,但考虑使用 table variable
并像下面那样使用
DECLARE @ExcludedList table(lastname varchar(30));
insert into @ExcludedList
SELECT TOP 20 Lastname
FROM dbo.Subscribers where [Firstname] = 'Dave';
SELECT [Firstname], Count([Firstname]) as [Count] from Subscribers
WHERE [Lastname] not in (select lastname from @ExcludedList);
如果需要使用变量,则必须是table变量:
DECLARE @ExcludedList TABLE (Lastname VARCHAR(MAX))
INSERT INTO @ExcludedList
SELECT TOP 20 Lastname
FROM dbo.Subscribers
WHERE [Firstname] = 'Dave'
SELECT [Firstname], Count([Firstname]) AS [Count]
FROM Subscribers
WHERE [Lastname] NOT IN (SELECT Lastname FROM @ExcludedList)