0

我想计算属于一个类别的所有记录并获取与最新记录关联的数据

CREATE TABLE #TestTable

(

SomeColumn VARCHAR(1)
,data varchar(50)
,CDate datetime
)

GO

INSERT INTO #TestTable VALUES ('A','abdss',getdate())
INSERT INTO #TestTable VALUES ('A','abserts',getdate())
INSERT INTO #TestTable VALUES ('A','awabs',getdate())
INSERT INTO #TestTable VALUES ('A','abrfgts',getdate())
INSERT INTO #TestTable VALUES ('A','abasds',getdate())
INSERT INTO #TestTable VALUES ('A','abasds',getdate())
INSERT INTO #TestTable VALUES ('A','aberzsdsfs',getdate())
INSERT INTO #TestTable VALUES ('A','abarfzdfs',getdate())
INSERT INTO #TestTable VALUES ('B','abzdsfs',getdate())

--SELECT * , COUNT(SomeColumn) From #TestTable
--GROUP BY SomeColumn 

drop table  #TestTable

所需的输出将是

SomeColumn | Data          | Date              |Other Associates Records <br/>
A          | abarfzdfs     |last A record date   |7<br/>
B          | abzdsfs       |last B record date   |0<br/>
4

1 回答 1

0

您尚未指定您使用的 sql server 版本。但是,如果您使用的是 sql-server 2005+。可能是这样的:

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY SomeColumn ORDER BY CDate) AS RowNbr,
        COUNT(SomeColumn) OVER(PARTITION BY SomeColumn) AS Counts,
        test.*
    FROM
        #TestTable AS test
)
SELECT
    *
FROM
    CTE
WHERE
    CTE.RowNbr=1
于 2012-05-03T06:18:52.300 回答