为每个类别获取一个顶部图像

时间:2012-02-01 06:52:39

标签: tsql

我将照片分组。 (2个表类别和catID字段的照片)

我有一个查询,它返回一个类别列表及其拥有的照片数量和顶部照片的图像名称(每张照片记录都有一个字段IsTop)。

但它不能正常工作。它只返回第一条记录的imagepath。休息时,它返回null

select
T3.ImagePath,T2.ID,T2.Title,T2.ItemsCount 
from (
select C.Title,C.ID,Count(Ph.CatID) as ItemsCount from Categories C
    left Outer join (select CatID from photos) Ph
    on C.ID=Ph.CatID group by C.Title,C.ID) T2 
left outer join 
(select top 1 ImagePath,CatID from photos where IsTop=1 order by id desc) T3 
on T2.ID=T3.CatID 
group by T3.ImagePath,T2.ID,T2.Title,T2.ItemsCount;

1 个答案:

答案 0 :(得分:1)

假设您使用的是SQL Server 2005或更高版本,则可以使用windowing function

select
T3.ImagePath,T2.ID,T2.Title,T2.ItemsCount 
from (
select C.Title,C.ID,Count(Ph.CatID) as ItemsCount from Categories C
    left Outer join (select CatID from photos) Ph
    on C.ID=Ph.CatID group by C.Title,C.ID) T2 
left outer join 
(select ImagePath,CatID,ROW_NUMBER() OVER (PARTITION BY CatID ORDER BY ID desc) as rn from photos where IsTop=1) T3 
on T2.ID=T3.CatID and rn = 1 /* <-- New join condition also */
group by T3.ImagePath,T2.ID,T2.Title,T2.ItemsCount;

在这种情况下,它允许我们对行进行编号,为每个CatIDPARTITION BY位)独立分配行号,并使用特定的顺序。对于每个CatID,我们从1开始再次分配行号。