create table #mytest(id int IDENTITY(1,1),value1 int,value2 int)
insert into #mytest(value1,value2)
values(10,20),(20,25),(30,50)
select * from #mytest where (value2-value1)=(select MIN(value2-value1) from #mytest)
select top 1 * from #mytest order by (value2-value1)
还有其它的方法么?哪种方法效率最高?(数据库表记录百万级)
------解决思路----------------------
实际上,第一个要快很多,
USE ADVENTUREWORKS2012;
GO
CREATE TABLE #T(ID INT IDENTITY(1,1),VAL INT, VAL2 INT, VAL3 AS VAL2-VAL)
INSERT INTO #T VALUES
(1,4)
GO 1000000
UPDATE #T
SET VAL2 = VAL2+ID
SET STATISTICS IO ON;
SET STATISTICS TIME ON;
--1
SELECT * FROM #T WHERE (VAL2-VAL)=(SELECT MIN(VAL2-VAL) FROM #T) OPTION(MAXDOP 4);
--2
SELECT TOP 1 * FROM #T ORDER BY (VAL2-VAL) OPTION(MAXDOP 4);
SET STATISTICS IO OFF;
SET STATISTICS TIME OFF;
------解决思路----------------------
第一句可以 再加个top 1 就行
select top 1 value1,value2 from #mytest where (value2-value1)=(select MIN(value2-value1) from #mytest)