我正在使用此代码:(来自这个问题:How to get the last record per group in SQL替换我自己的列)
WITH e AS
(
SELECT *,
ROW_NUMBER() OVER
(
PARTITION BY ApplicationId
ORDER BY theDate DESC
) AS Recency
FROM [Event]
)
SELECT *
FROM e
WHERE Recency = 1
仅当两个字段相同时才可以“分区”吗?例如,我有这样的数据:
ID Name theDate
123 John 01/01/2012
123 John 01/02/2012
123 Doe 01/01/2012
456 Smith 02/04/2012
789 Smith 02/01/2012
789 Smith 02/09/2012
789 Roger 02/08/2012
根据这些数据,我想回复:
ID Name theDate
123 John 01/02/2012
123 Doe 01/01/2012
456 Smith 02/04/2012
789 Smith 02/09/2012
789 Roger 02/08/2012
感谢您的帮助。
托马斯
答案 0 :(得分:32)
您可以使用逗号分隔多个列
WITH e AS
(
SELECT *,
ROW_NUMBER() OVER
(
PARTITION BY ApplicationId , Name
ORDER BY theDate DESC
) AS Recency
FROM [Event]
)
SELECT *
FROM e
WHERE Recency = 1
答案 1 :(得分:3)
我在这里找到答案:Table partitioning using 2 columns
您只能对1列进行分区,但是可以生成该列以创建“多个分区”,如下所示:
WITH e AS
(
SELECT *,
ROW_NUMBER() OVER
(
PARTITION BY CONVERT(VARCHAR(100),ApplicationId) + ' ' + Name
ORDER BY theDate DESC
) AS Recency
FROM [Event]
)
SELECT *
FROM e
WHERE Recency = 1
将两列作为一个单独的字符串添加在一起,确保只有在两列完全相同时才会进行分区。