以下是 SQL Server 2012+、2005 到 2008 R2 和 2000 的单独解决方案:
2012+
CREATE TABLE #PlayerPoints
( ID INT PRIMARY KEY
, Name VARCHAR(10) NOT NULL
, Email VARCHAR(20) NOT NULL
, Points INT NOT NULL);
INSERT INTO #PlayerPoints (ID, Name, Email, Points)
VALUES
(1, 'John', 'john@aaa.com', 120)
, (2, 'Test', 'bob@aaa.com', 100)
, (3, 'John', 'john@bbb.com', 80)
, (4, 'Bob', 'bob@aaa.com', 50)
, (5, 'John', 'john@aaa.com', 80)
WITH BaseData
AS
(SELECT ID
, Email
, Points
, LastRecordName = LAST_VALUE(Name) OVER
(PARTITION BY Email
ORDER BY ID DESC
ROWS UNBOUNDED PRECEDING)
FROM #PlayerPoints)
SELECT Email
, LastRecordName = MAX(LastRecordName)
, Points = SUM(Points)
, Games_Played = COUNT(*)
, Average_Points = AVG(Points)
FROM BaseData
GROUP BY Email
ORDER BY Points DESC;
2005 至 2008 R2
CREATE TABLE #PlayerPoints
( ID INT PRIMARY KEY
, Name VARCHAR(10) NOT NULL
, Email VARCHAR(20) NOT NULL
, Points INT NOT NULL);
INSERT INTO #PlayerPoints (ID, Name, Email, Points)
VALUES
(1, 'John', 'john@aaa.com', 120)
, (2, 'Test', 'bob@aaa.com', 100)
, (3, 'John', 'john@bbb.com', 80)
, (4, 'Bob', 'bob@aaa.com', 50)
, (5, 'John', 'john@aaa.com', 80)
WITH BaseData
AS
(SELECT ID
, Email
, Name
, ReverseOrder = ROW_NUMBER() OVER
(PARTITION BY Email
ORDER BY ID DESC)
FROM #PlayerPoints)
SELECT pp.Email
, LastRecordName = MAX(bd.Name)
, Points = SUM(pp.Points)
, Games_Played = COUNT(*)
, Average_Points = AVG(pp.Points)
FROM #PlayerPoints pp
JOIN BaseData bd
ON pp.Email = bd.Email
AND bd.ReverseOrder = 1
GROUP BY pp.Email
ORDER BY Points DESC;
2000
CREATE TABLE #PlayerPoints
( ID INT PRIMARY KEY
, Name VARCHAR(10) NOT NULL
, Email VARCHAR(20) NOT NULL
, Points INT NOT NULL);
INSERT INTO #PlayerPoints (ID, Name, Email, Points)
SELECT 1, 'John', 'john@aaa.com', 120
UNION ALL
SELECT 2, 'Test', 'bob@aaa.com', 100
UNION ALL
SELECT 3, 'John', 'john@bbb.com', 80
UNION ALL
SELECT 4, 'Bob', 'bob@aaa.com', 50
UNION ALL
SELECT 5, 'John', 'john@aaa.com', 80;
SELECT pp.Email
, LastRecordName = MAX(sppmi.Name)
, Points = SUM(pp.Points)
, Games_Played = COUNT(*)
, Average_Points = AVG(pp.Points)
FROM #PlayerPoints pp
JOIN
(SELECT spp.Email
, spp.Name
FROM #PlayerPoints spp
JOIN
(SELECT Email
, MaximumID = MAX(ID)
FROM #PlayerPoints
GROUP BY Email) mi
ON spp.ID = mi.MaximumID) sppmi
ON pp.Email = sppmi.Email
GROUP BY pp.Email
ORDER BY Points DESC;