Postgresql – SQL Select query with postgresql

postgresql

I'd like to find all rows if is shows even once a particular value with postgresql

For example :

id   TIT_CODE  CLI_NOM   CLI_PRENOM  CLI_ENSEIGNE
  1  M.        DUPONT    Alain       A
  2  M.        MARTIN    Marc        A
  3  M.        BOUVIER   Alain       V
  4  M.        DUBOIS    Paul        D
  5  M.        DREYFUS   Jean        C
  6  M.        FAURE     Alain       C
 11  M.        DUPONT    Alain       B
 12  M.        DUVAL     Arsène      B
 13  M.        DUPONT    Alain       B
 16  M.        CHABAUD   Daniel      A

And I want to have all rows where CLI_ENSEIGNE = 'A' but not only I want also the rows where CLI_NOM had a CLI_ENSEIGNE = 'A' even only one time:

We see here the Dupond had an A the a B

id   TIT_CODE  CLI_NOM   CLI_PRENOM  CLI_ENSEIGNE
  1  M.        DUPONT    Alain       A
  2  M.        MARTIN    Marc        A
 11  M.        DUPONT    Alain       B
 13  M.        DUPONT    Alain       B
 16  M.        CHABAUD   Daniel      A

I tried

SELECT 
  *
FROM 
  table
WHERE 
CLI_ENSEIGNE = 'A' 
IN (CLI_NOM)

But it's saying that CLI_NOM doesn't exists

Best Answer

You where clause is incomplete and wouldn't work that way anyway.

You need a subselect for this:

SELECT   *
FROM the_table
WHERE cli_nom in (select cli_nom 
                  from the_table
                  where CLI_ENSEIGNE = 'A' );

alternatively a co-related sub-select with an exists clause:

SELECT t1.*
FROM the_table t1
WHERE EXISTS (select 42
              from the_table t2
              where t2.cli_nom = t1.cli_nom
                and CLI_ENSEIGNE = 'A' );