SQL INTERSECT与最匹配的结果

时间:2016-05-26 07:24:01

标签: sql sql-server-2005

我有一个与SQL脚本相关的问题:

如果我这样做:

DECLARE @ProfileID int
SET @ProfileID = 1

SELECT [SetID],[ProfileID]
FROM [GeneralizedTable].[dbo].[DBProfileConditionTable]

where ([DBTypeID] = 4 AND ([ProfileID] = 1 OR [ProfileID] = 3 OR [ProfileID] = 13) AND [ConditionID] = 1 AND [CondMin] between 0 and 0 AND [CondMax] between 1000 and 1000)

group by [SetID], [ProfileID]

ORDER BY ABS([ProfileID] - @ProfileID)

这将对与Top = 1最匹配的结果进行排序。

但是如果我添加一些INTERSECT子句来构造多个搜索,会弹出错误“关键字'INTERSECT'附近的语法不正确”

最后一句是:

DECLARE @ProfileID int
SET @ProfileID = 1

SELECT [SetID],[ProfileID]
FROM [GeneralizedTable].[dbo].[DBProfileConditionTable]

where ([DBTypeID] = 4 AND ([ProfileID] = 1 OR [ProfileID] = 3 OR [ProfileID] = 13) AND [ConditionID] = 1 AND [CondMin] between 0 and 0 AND [CondMax] between 1000 and 1000)

group by [SetID], [ProfileID]

ORDER BY ABS([ProfileID] - @ProfileID)

INTERSECT

SELECT [SetID], [ProfileID]
FROM [GeneralizedTable].[dbo].[DBProfileConditionTable]

where ([DBTypeID] = 4 AND ([ProfileID] = 1 OR [ProfileID] = 3 OR [ProfileID] = 13) AND [ConditionID] = 3 AND [CondMin] between 0 and 0 AND [CondMax] between 200 and 200)

group by [SetID], [ProfileID]

ORDER BY ABS([ProfileID] - @ProfileID)

INTERSECT
SELECT [SetID], [ProfileID]
FROM [GeneralizedTable].[dbo].[DBProfileParameterSetTable]

where ([DBTypeID] = 4 AND ([ProfileID] = 1 OR [ProfileID] = 3 OR [ProfileID] = 13) AND [BondClassificationID] = 0 AND [BondObjectID] = 0)

group by [SetID], [ProfileID]

ORDER BY ABS([ProfileID] - @ProfileID)

正在运行的SQL Server是SQL Server 2005.你能告诉我导致这个错误的部分是错误的以及如何解决

这使它有效吗?感谢。

1 个答案:

答案 0 :(得分:1)

比我最初想的要复杂得多,但这应该有效(虽然我没有测试它......):

DECLARE @ProfileID int
SET @ProfileID = 1

SELECT  [SetID],[ProfileID]
FROM    (
SELECT [SetID],[ProfileID]
FROM [GeneralizedTable].[dbo].[DBProfileConditionTable]

where ([DBTypeID] = 4 AND ([ProfileID] = 1 OR [ProfileID] = 3 OR [ProfileID] = 13) AND [ConditionID] = 1 AND [CondMin] between 0 and 0 AND [CondMax] between 1000 and 1000)

group by [SetID], [ProfileID]


INTERSECT

SELECT [SetID], [ProfileID]
FROM [GeneralizedTable].[dbo].[DBProfileConditionTable]

where ([DBTypeID] = 4 AND ([ProfileID] = 1 OR [ProfileID] = 3 OR [ProfileID] = 13) AND [ConditionID] = 3 AND [CondMin] between 0 and 0 AND [CondMax] between 200 and 200)

group by [SetID], [ProfileID]


INTERSECT
SELECT [SetID], [ProfileID]
FROM [GeneralizedTable].[dbo].[DBProfileParameterSetTable]

where ([DBTypeID] = 4 AND ([ProfileID] = 1 OR [ProfileID] = 3 OR [ProfileID] = 13) AND [BondClassificationID] = 0 AND [BondObjectID] = 0)

group by [SetID], [ProfileID]
) a

ORDER BY ABS([ProfileID] - @ProfileID)