示例:假设原始表包含以下值
AcctNbr StatusDate
------------------
123 01/01/2012
123 01/01/2013
123 12/11/2011
987 01/01/2009
SQL 将创建一个新表,其中包含
AcctNbr EarliestStatusDate LatestStatusDate
-------------------------------------------
123 12/11/2011 01/01/2013
987 01/01/2009 01/01/2009
我正在寻找一种有效的方法来做到这一点。我有一个有效的方法,但它需要很长的时间。有没有人有任何优化提示。任何帮助将不胜感激。
SET NOCOUNT ON
DROP TABLE loopTemp
DROP TABLE reportTemp
CREATE TABLE loopTemp
( ID int IDENTITY(1, 1) NOT NULL,
AcctNbr varchar(50),
)
CREATE TABLE reportTemp
(
AcctNbr varchar(50),
EarliestStatus Date,
LatestStatus Date
)
INSERT INTO loopTemp
SELECT DISTINCT AcctNbr
FROM AutoStatusHistory
DECLARE @COUNTER AS INT
SET @COUNTER = 1
DECLARE @MAX AS INT
SET @MAX = (SELECT MAX(ID) FROM loopTemp)
WHILE @COUNTER < @MAX BEGIN
DECLARE @ACCOUNT_NUMBER AS varchar(50)
SET @ACCOUNT_NUMBER =
(SELECT AcctNbr FROM loopTemp WHERE ID = @COUNTER)
DECLARE @EARLIESTSTATUSDATE AS DATE
SET @EARLIESTSTATUSDATE = (SELECT MIN(NewStatusDate)
FROM AutoStatusHistory
WHERE AcctNbr = @ACCOUNT_NUMBER)
DECLARE @LATESTSTATUSDATE AS DATE
SET @LATESTSTATUSDATE = (SELECT MAX(NewStatusDate)
FROM AutoStatusHistory
WHERE AcctNbr = @ACCOUNT_NUMBER)
INSERT INTO reportTemp
VALUES (@ACCOUNT_NUMBER, @EARLIESTSTATUSDATE, @LATESTSTATUSDATE)
IF (@COUNTER % 1000) = 0 BEGIN
PRINT @COUNTER
END -- IF
SET @COUNTER = @COUNTER + 1
END -- WHILE
DROP TABLE loopTemp