我想写一个sql server 2008查询,按照下表中公布的最新日期排序的brandId选择最不同的产品:
dbo.Products
ProductId, BrandId, PublishedOn
表格内容:
1, 1, 2011-01-01
2, 2, 2011-01-01
3, 3, 2011-01-01
4, 1, 2011-01-09
5, 1, 2011-01-10
6, 2, 2011-01-10
我之后的输出是:
6, 2, 2011-01-10
5, 1, 2011-01-10
3, 3, 2011-01-01
任何人都知道如何实现这一目标?
如果标题不正确,我很抱歉,但我不知道该怎么说这个。
答案 0 :(得分:2)
您希望BrandId
订购每个PublishedOn
的最新行?
;WITH T
AS (SELECT *,
ROW_NUMBER() OVER (PARTITION BY BrandId
ORDER BY PublishedOn DESC) AS RN
FROM dbo.Products)
SELECT ProductId,
BrandId,
PublishedOn
FROM T
WHERE RN = 1