表product。
productid(主键),dealerid(商家id),pic(图片),productname(产品名称)
1 1 url1 a
2 1 url2 b
3 2 url3 c
根据dealerid分组,每个dealerid只能取出一行数据。注意是一行数据。
比如这个可以取出 2,3两行或者1,3两行。
这样的sql不可以的
select dealerid,max(productid),max(pic),max(productname) from product group by dealerid
这样只保证了其他列取出一个,并不能保证取出的都是一行的。
------最佳解决方案--------------------
不可以。
SELECT * FROM product WHERE productid IN (
SELECT MAX(productid) FROM product GROUP BY dealerid
)
------其他解决方案--------------------
select * from product where productid in (select MAX(productid) from product group by dealerid)
------其他解决方案--------------------
if object_id('[product]') is not null drop table [product]
go
create table [product] (productid int,dealerid int,pic nvarchar(8),productname nvarchar(2))
insert into [product]
select 1,1,'url1','a' union all
select 2,1,'url2','b' union all
select 3,2,'url3','c'
select * from [product]
SELECT *
FROM product P
WHERE NOT EXISTS ( SELECT 1
FROM product M
WHERE P.dealerid = M.dealerid
AND P.pic > M.pic ) --选最大或最小,lz可以从这里调整
/*
productid dealerid pic productname
----------- ----------- -------- -----------
1 1 url1 a
3 2 url3 c
(2 行受影响)
*/
------其他解决方案--------------------
2005以后可用:
;
WITH huang
AS ( SELECT ROW_NUMBER() OVER ( PARTITION BY dealerid ORDER BY productid ) pid ,