1. 程式人生 > >SqlServer中 Partition By 的使用

SqlServer中 Partition By 的使用

1:資料庫表結構:

(產品圖片表)

select * from product_imgs


2:應用場景:

可見表中每一個產品(pro_id)可能對應多個圖片(img),我想要按照新增時間的先後順序,獲得其中每一個產品的第一張圖片

3:嘗試使用 group by 

select top 1 pro_id,img,create_time from product_imgs group by pro_id,img,create_time order by create_time 

發現無法滿足每一個產品的圖片

4:使用Partition by 

select * from (select pro_id,img,create_time, ROW_NUMBER() over(partition by pro_id order by  create_time) as row_sort  from product_imgs )
  as t where t.row_sort=1

可以滿足需求,所以Partition by可以理解為 對多行資料分組後排序取每個產品的第一行資料

--以下20180712修改

最近又發現  cross apply 在聯表的時候可以代替 partition by ,查詢的效果是一樣的

select a.id,a.title,t.* from Product as a
cross apply 
(select top 1 b.pro_id,b.img  from product_imgs as b where b.pro_id=a.id)
as t

注:inner join 和 cross apply的不同,點選 https://blog.csdn.net/liuchang19950703/article/details/81015853