SQL:为现有表中的其他列创建具有不同值和最大/最小值的新表

时间:2013-03-21 14:01:02

标签: sql sql-server

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

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

3 个答案:

答案 0 :(得分:2)

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

SELECT AcctNbr, MIN(StatusDate) AS EarliestStatusDate, 
    MAX(StatusDate) AS LatestStatusDate
FROM myTable
GROUP BY AcctNbr

答案 1 :(得分:0)

您似乎正在使用SQL Server。为此,您可以:

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

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

into #ReportTemp

答案 2 :(得分:0)

您可以使用

SELECT *
INTO TableName
FROM (
SELECT AcctNbr, MIN([Status Date]) AS EarliestStatusDate, 
    MAX([Status Date]) AS LatestStatusDate
FROM myTable
GROUP BY AcctNbr
) RequiredData