繁体   English   中英

Select 在 SQL 服务器中只有 max(id) 行

[英]Select ONLY row with max(id) in SQL SERVER

我有一张表 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

我想要 select 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

你可以试试看

Select Max(ID),ProductCatId,ProductCode,price
From TableName
Group By ProductCatId,ProductCode,price
select 
top 1 with ties
ID,ProductCatId,ProductCode,Price
from
table
order by
row_number() over (partition by productcatid order by id desc)

可以使用row_number()

select t.*
from (select t.*,
             row_number() over (partition by ProductCatId order by ID desc) as seqnum
      from @Table t
     ) t
where seqnum = 1
order by ID;

短一点:

SELECT DISTINCT 
    max(ID) OVER (PARTITION BY ProductCatId, 
                               ProductCode, 
                               Price) AS ID,
    ProductCatId, 
    ProductCode, 
    Price,
  FROM myTable

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM