1

示例:假设原始表包含以下值

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
4

3 回答 3

2

除非我遗漏了什么,否则这应该非常简单:

SELECT AcctNbr, MIN(StatusDate) AS EarliestStatusDate, 
    MAX(StatusDate) AS LatestStatusDate
FROM myTable
GROUP BY AcctNbr
于 2013-03-21T14:03:54.420 回答
0

您可以使用

SELECT *
INTO TableName
FROM (
SELECT AcctNbr, MIN([Status Date]) AS EarliestStatusDate, 
    MAX([Status Date]) AS LatestStatusDate
FROM myTable
GROUP BY AcctNbr
) RequiredData
于 2013-03-21T14:09:48.193 回答
0

您似乎正在使用 SQL Server。为此,您可以执行以下操作:

select AcctNbr, min(StatusDate) as EarliestStatusDate,
       max(StatusDate) as LatestStatusDate
into ReportTemp
from AutoStatusHistory
group by AcctNbr

into语句将结果保存到表中。您可能希望使用实际的临时表,语法如下:

into #ReportTemp
于 2013-03-21T14:06:14.043 回答