坚持使用简单的select语句来返回单行

时间:2013-11-08 10:21:12

标签: sql-server-2008 select

有一个非常简单的选择语句,我需要执行,由于某种原因无法绕过它,即使我以前做过这些。我有一张表格如下:

CustomerNo  Code    FA  DateDUE
8625475   SAFETY    A   05/02/2014
8625475   REVIEW    A   18/06/2014
8625475   CHECK     C   18/06/2014
8885742   REVIEW    A   23/01/2014
8885742   TEST      B   23/01/2014

更新的问题更清楚:我需要选择FA代码为A的数据,唯一带有A的代码是REVIEW,所以在上面的select语句中它只返回一个客户编号(8885742) - 希望这更清楚

1 个答案:

答案 0 :(得分:3)

如果您想要客户的所有记录:

select * from your_table
where customerNo in
(
  select customerno 
  from your_table
  where FA = 'A'
  group by customerno
  having sum(case when code <> 'REVIEW' then 1 else 0 end) = 0
)

如果您只需要customerno

  select customerno 
  from your_table
  where FA = 'A'
  group by customerno
  having sum(case when code <> 'REVIEW' then 1 else 0 end) = 0

SQLFiddle demo