如何根据条件使用SQL查询从表中选择特定行数?

时间:2017-04-25 12:24:09

标签: sql-server

我将照片图像存储在SQL Server数据库中。使用名为PhotoType的列存储图像。

PhotoTypes很多 - 其中一些是:

CheckList, Installation, Audit, SignOff ...

现在我想从CheckList中选择2张照片,2张照片用于安装,1张照片用于审核,1张照片用于SignOff,从数据库中选择(针对每位客户)。

因此,共有6张照片可供选择,但数据库可能会为客户提供许多照片。

如何在SQL查询中执行此操作?

谢谢和问候

克里希纳

2 个答案:

答案 0 :(得分:0)

common table expression使用row_number()

;with cte as (
  select *
    , rn = row_number() over (
      partition by Customer, PhotoType
      order by Id)
  from Photo 
  where PhotoType in ('CheckList','Installation','Audit','SignOff')
)
select *
from cte
where rn = 1 
  or (rn = 2 and PhotoType in ('CheckList','Installation');

使用子查询(派生表)而不是cte

select *
from (
  select *
    , rn = row_number() over (
      partition by Customer, PhotoType
      order by Id)
  from Photo 
  where PhotoType in ('CheckList','Installation','Audit','SignOff')
  ) as sub
where rn = 1 
  or (rn = 2 and PhotoType in ('CheckList','Installation');

答案 1 :(得分:0)

   select top 2 * from temp# where [Type]='CheckList'
   union all
   select top 2 * from temp# where [Type]='Installation'
   union all
   select top 1 * from temp# where [Type]='Audit'
   union all
   select top 1 * from temp# where [Type]='SignOff'