让我想象我有一张像
这样的表name time_stamp quantity
John 2017-11-28 08:46:01 65
Clark 2017-11-28 08:44:08 98
John 2017-11-28 08:50:54 74
我需要的是按名称对其进行分组,并从最新记录中获取数据。我无法按名称分组,因为个人电脑不知道应该为John使用哪些数据。我需要像
这样的输出name time_stamp quantity
Clark 2017-11-28 08:44:08 98
John 2017-11-28 08:50:54 74
因为65岁是老记录然后是74 ..
我试过了SELECT name, MAX(time_stamp) AS time_stamp, quantity FROM table1 GROUP BY time_stamp
,但它并不适合我,因为 -
列' table1.name'在选择列表中无效,因为它不是 包含在聚合函数或GROUP BY子句中。
答案 0 :(得分:2)
WITH CTE AS(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY [name] ORDER BY time_stamp DESC) AS RN
FROM YourTable)
SELECT *
FROM CTE
WHERE RN = 1;
答案 1 :(得分:0)
您可以使用派生表来选择max(time_stamp)。
SELECT T1.*
FROM (
SELECT [name]
,MAX(time_stamp) AS MAXtime_stamp --MAX time_stamp by name
FROM table1
GROUP BY [name]
) AS dT INNER JOIN table1 T1 ON dT.MAXtime_stamp = T1.time_stamp
AND dT.[name] = T1.[name]