我想要完成的事情
从表格中选择最多两条记录,其中包含过去两年内Test1-Test8字段中的一些代码。
但是这两个记录不能有任何重复的代码。
即表示Record1在Test4中包含'85 .43' 和Record2在Test2中包含'85 .43'
我不希望它返回Record2,因为已经存在'85 .43'的记录。
任何人都知道如何实现这一目标?
这是我的初始查询,它没有内置重复逻辑。
select TOP 2 * from Visit where customer = CustomerCode AND
(Test1 IN ('85.41', '85.43', '85.45', '85.47')
or Test2 IN ('85.41', '85.43', '85.45', '105.47')
or Test3 IN ('85.41', '85.43', '85.45', '105.47')
or Test4 IN ('85.41', '85.43', '85.45', '105.47')
or Test5 IN ('85.41', '85.43', '85.45', '105.47')
or Test6 IN ('85.41', '85.43', '85.45', '105.47')
or Test7 IN ('85.41', '85.43', '85.45', '105.47')
or Test8 IN ('85.41', '85.43', '85.45', '105.47'))
AND TIMESTAMPDIFF(SQL_TSI_MONTH, DATE_IN, CurrentDate) <= 24;
由于
答案 0 :(得分:2)
这是我能想到的最干净的方式,而不需要直接使用表格所需的所有64次比较:
CREATE TABLE #t (ID int, TestField varchar(255))
INSERT INTO #t SELECT Id, Test1 FROM Visit WHERE customer = CustomerCode AND TIMESTAMPDIFF(SQL_TSI_MONTH, DATE_IN, CurrentDate) <= 24
INSERT INTO #t SELECT Id, Test2 FROM Visit WHERE customer = CustomerCode AND TIMESTAMPDIFF(SQL_TSI_MONTH, DATE_IN, CurrentDate) <= 24
INSERT INTO #t SELECT Id, Test3 FROM Visit WHERE customer = CustomerCode AND TIMESTAMPDIFF(SQL_TSI_MONTH, DATE_IN, CurrentDate) <= 24
... -- repeat for each Test field
SELECT TOP 2 * FROM Visit WHERE Id IN (
SELECT a.Id FROM #t a
LEFT JOIN #t b
ON a.Id > b.Id
AND a.TestField = b.TestField
GROUP BY a.Id
HAVING count(b.TestField) = 0
)
ORDER BY Id
DROP TABLE #t
根据表的大小,您可能需要向临时表添加索引,否则速度将无法忍受:
CREATE INDEX some_unique_name_index ON #t (ID, TestField)
另一种加快速度的方法是使用T-SQL循环一次找到符合条件的一行,并将它们添加到结果表中。一旦你有足够的结果(在这种情况下为2),你可以退出循环。对于非常大的表,这可能是推荐的方法。