复杂的SQL查询请求

时间:2019-01-23 10:00:32

标签: sql

我有一张桌子

Number    Letter    KeyLetter

1         a         1
1         b         0
1         c         0
1         d         0

2         e         0
2         f         0
2         g         0

3         h         1
3         i         1
3         j         0

我想要它:

Number    Letter    KeyLetter

1         a         1

2         e         0
2         f         0
2         g         0

3         h         1
3         i         1

对于每组数字,如果一个字母是一个KeyLetter,我想忽略所有非KeyLetter。 如果一组数字中没有字母是KeyLetter的条目,则显示该组数字中的所有条目。

哪些SQL查询将能够做到这一点?

1 个答案:

答案 0 :(得分:2)

简单答案,返回KeyLetter = 1的行,以及Number不具有KeyLetter = 1的行。

select *
from tablename t1
where t1.KeyLetter = 1
   or not exists (select * from tablename t2
                  where t1.Number = t2.Number
                    and t2.KeyLetter = 1)

或者:

select t1.*
from tablename t1
join (select Number, max(KeyLetter) maxKeyLetter
      from tablename
      group by Number) t2
  on t1.Number = t2.Number and t1.KeyLetter = t2.maxKeyLetter

或者...

select *
from tablename
where (Number, KeyLetter) in 
    (select Number, max(KeyLetter)
     from tablename
     group by Number)

前两个是Core ANSI SQL兼容的。后者使用扩展名F641,“行和表的构造函数”。