0

I have a question about a topic that was already discussed:

select rows having condition met for group (without temporary table)

Let's say I have:

ID Name Account Year
1 Jack 0001 1928
2 John 0001 1908
3 Mary 0001 1918
4 Paul 0002 1899
5 James 0002 1913
6 Laura 0003 1925

By using EXISTS clause as shown in the link:

SELECT d.ID, d.Name d.Account, d.Year
FROM data a
WHERE EXISTS (
    SELECT 1 FROM data b WHERE Year < 1920 AND a.Account = b.Account
) ;

I obtain the Output:

ID Name Account Year
1 Jack 0001 1928
2 John 0001 1908
3 Mary 0001 1918
4 Paul 0002 1899
5 James 0002 1913

What query should i use in order to obtain:

ID Name Account Year
4 Paul 0002 1899
5 James 0002 1913

If Year < 1920 at least for one line, no line from the "Account" field will not be selected.

3
  • What if you replace EXISTS with NOT EXISTS? Feb 15 at 15:33
  • I modified my question in order to be easier to understand. If I use NOT EXISTS i obtain all the records where year > 1925
    – Paul Soare
    Feb 15 at 17:44
  • That doesn't make any sense, 1925 doesn't appear in your query so how could it behave that way? Please show us a fiddle or something (dbfiddle.uk)
    – jjanes
    Feb 15 at 22:14

1 Answer 1

1

Rather than saying,

Return this row if another row with the same Account exists that has Year less than 1920

you should be saying,

Return this row if no other rows with the same Account exist that have Year of 1920 or above (not less than 1920),

thus putting NOT in two locations of your current condition:

NOT EXISTS ( ... NOT (Year < 1920) )

This is the entire query:

SELECT
  *
FROM
  data AS this
WHERE
  NOT EXISTS
  (
    SELECT
      *
    FROM
      data AS that
    WHERE
      that.Account = this.Account
      AND NOT (that.Year < 1920)
      -- or: AND that.Year >= 1920
  )
;
1
  • Ok, thank you for your reply, it works great for me.
    – Paul Soare
    Feb 16 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.