Mat*_*th9 1 sql sql-server sql-server-2008
我有一张表 A :
ID     | ProductCatId | ProductCode | Price
1      |       1      |  PROD0001   | 2
2      |       2      |  PROD0005   | 2
3      |       2      |  PROD0005   | 2
4      |       3      |  PROD0008   | 2
5      |       5      |  PROD0009   | 2
6      |       7      |  PROD0012   | 2
我想选择 ID、ProductCatId、ProductCode、Price,条件为: “如果 ProductCatId 存在相同的值,则使用 max(ID) 获取 ProductCatId”,例如:
ID     | ProductCatId | ProductCode | Price
1      |       1      |  PROD0001   | 2
3      |       2      |  PROD0005   | 2
4      |       3      |  PROD0008   | 2
5      |       5      |  PROD0009   | 2
6      |       7      |  PROD0012   | 2
寻找窗口函数和 row_number()
select ID , ProductCatId , ProductCode , Price
  from (
        select ID , ProductCatId , ProductCode , Price, row_number() over (partition by ProductCatId order by ID desc) as rn
         from myTable
        ) as t
  where t.rn = 1
| 归档时间: | 
 | 
| 查看次数: | 12288 次 | 
| 最近记录: |