简体   繁体   中英

Complicated SQL query request

I have a table

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

From it I want this:

Number    Letter    KeyLetter

1         a         1

2         e         0
2         f         0
2         g         0

3         h         1
3         i         1

For each set of numbers, if a letter is a KeyLetter, I want to ignore any non KeyLetters. If a set of numbers doesn't have an entry where the letter is a KeyLetter, then show all of the entries in that set of numbers.

What SQL query would be able to do this?

Simple answer, return the rows with KeyLetter = 1, and also those with a Number not having a 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)

Alternatively:

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

Or...

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

The first two are Core ANSI SQL compliant. The latter one uses extension F641, "Row and table constructors".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM