22,210
社区成员
发帖
与我相关
我的任务
分享
--> 生成测试数据表: [tb]
IF OBJECT_ID('[tb]') IS NOT NULL
DROP TABLE [tb]
GO
CREATE TABLE [tb] ([ID] [int],[Product_ID] [int],[Product_picture] [nvarchar](40))
INSERT INTO [tb]
SELECT '1','1','productImage/1111111105.jpg' UNION ALL
SELECT '784','1','productImage/1111111105_784.jpg' UNION ALL
SELECT '785','1','productImage/1111111105_785.jpg' UNION ALL
SELECT '2','2','productImage/1111121402.jpg' UNION ALL
SELECT '3','2','productImage/1111121402_3.jpg' UNION ALL
SELECT '4','3','productImage/1111121406.jpg' UNION ALL
SELECT '5','3','productImage/1111121406_8.jpg'
--SELECT * FROM [tb]
-->SQL查询如下:
SELECT * FROM tb t WHERE id=(SELECT MAX(id) FROM tb WHERE Product_ID=t.Product_ID)
/*
ID Product_ID Product_picture
----------- ----------- ----------------------------------------
785 1 productImage/1111111105_785.jpg
3 2 productImage/1111121402_3.jpg
5 3 productImage/1111121406_8.jpg
(3 行受影响)
*/
--> 测试数据: #tb
if object_id('tempdb.dbo.#tb') is not null drop table #tb
go
create table #tb (ID int,Product_ID int,Product_picture varchar(31))
insert into #tb
select 1,1,'productImage/1111111105.jpg' union all
select 784,1,'productImage/1111111105_784.jpg' union all
select 785,1,'productImage/1111111105_785.jpg' union all
select 2,2,'productImage/1111121402.jpg' union all
select 3,2,'productImage/1111121402_3.jpg' union all
select 4,3,'productImage/1111121406.jpg' union all
select 5,3,'productImage/1111121406_8.jpg'
Select Max(ID),product_ID,max(Product_picture) From #tb Group by product_id
select * from tb t where id=(select max(id) from tb where product_id=t.product_id)
select * from
(
select *, max(ID) over (partition by Product_ID) as MaxID
from Product
) Temp
where ID = MaxID
select * from #tb t
where not exists(select * from #tb where Product_ID=t.Product_ID and Product_picture>t.Product_picture)
select * from tb where id in (select max(id) from tb group by product_id)
Select Max(ID),product_ID,Product_picture From tb Group by product_id
--> 测试数据: #tb
if object_id('tempdb.dbo.#tb') is not null drop table #tb
go
create table #tb (ID int,Product_ID int,Product_picture varchar(31))
insert into #tb
select 1,1,'productImage/1111111105.jpg' union all
select 784,1,'productImage/1111111105_784.jpg' union all
select 785,1,'productImage/1111111105_785.jpg' union all
select 2,2,'productImage/1111121402.jpg' union all
select 3,2,'productImage/1111121402_3.jpg' union all
select 4,3,'productImage/1111121406.jpg' union all
select 5,3,'productImage/1111121406_8.jpg'
select * from #tb t
where not exists(select * from #tb where Product_ID=t.Product_ID and Product_picture>t.Product_picture)
ID Product_ID Product_picture
----------- ----------- -------------------------------
785 1 productImage/1111111105_785.jpg
3 2 productImage/1111121402_3.jpg
5 3 productImage/1111121406_8.jpg
(3 行受影响)