首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用SQL查询从表中根据条件选择特定的行数?

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

Stack Overflow用户
提问于 2017-04-25 12:24:09
回答 2查看 189关注 0票数 1

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

PhotoTypes有很多种--其中一些是:

代码语言:javascript
复制
CheckList, Installation, Audit, SignOff ...

现在,我希望从数据库中为CheckList选择2张照片、2张用于安装的照片、1张用于审核的照片和1张用于SignOff的照片(针对每个客户)。

因此,将有6张照片将被选中,虽然数据库可能有许多照片为客户。

如何在SQL查询中做到这一点?

感谢并致以问候

克里希纳

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-25 12:37:10

公共表表达式row_number()结合使用

代码语言:javascript
复制
;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

代码语言:javascript
复制
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');
票数 0
EN

Stack Overflow用户

发布于 2017-04-25 12:57:56

代码语言:javascript
复制
   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'
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43610582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档