日期:2014-05-17  浏览次数:20513 次

这个sql如何写?
表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    

这样只保证了其他列取出一个,并不能保证取出的都是一行的。

------最佳解决方案--------------------
2005以后可用:
;
WITH    huang
          AS ( SELECT   ROW_NUMBER() OVER ( PARTITION BY dealerid ORDER BY productid ) pid ,
                        productid ,
                        dealerid ,
                        pic ,
                        productname
               FROM     product
             )
    SELECT  *
    FROM    huang
    WHERE   pid = 1

------其他解决方案--------------------
use tempdb
go


if object_id('#') is not null drop table # 
create table #(productid int primary key,dealerid int,pic nvarchar(200),productname nvarchar(50))
insert into #(productid,dealerid,pic,productname) values
(1,1,'url1','a'),(2,1,'url2','b'),(3,2,'url3','c')


-- sql:
select * from #  a where a.productid=(select max(productid) from # where dealerid=a.dealerid)

------其他解决方案--------------------
--(1,3):
select * from #  a where a.productid=(select min(productid) from # where dealerid=a.dealerid)