No soy bueno con SQL, y quiero hacer algo que creo que es bastante simple. La siguiente consulta devuelve una tabla de ID de una columna:

select distinct(email_campaign_id) 
    from hubspot.email_events a
where a.subject in ('subject1', 'subject2', 'subject3')

Me gustaría usar esta columna de ID en otra consulta como esta:

with relevant_ids as
  (
  select distinct(email_campaign_id) 
      from hubspot.email_events a
  where a.subject in ('subject1', 'subject2', 'subject3')
  )

select * 
  from hubspot.email_events a
where a.email_campaign_id in relevant_ids

Sin embargo, esto arroja un error:

ERROR: syntax error at or near "relevant_ids"

¿Alguna idea de lo que estoy haciendo mal aquí? ¿Mi uso de 'con' es incorrecto?

sql
1
Canovice 18 ene. 2018 a las 23:25

3 respuestas

La mejor respuesta

Sólo:

select * 
  from hubspot.email_events a
where a.email_campaign_id in (   
                               select distinct(email_campaign_id) 
                               from hubspot.email_events a
                               where a.subject in ('subject1', 'subject2', 'subject3')
)

O si desea usar CTE, debe nombrar la columna en CTE si no se especifica el nombre de la columna, pero en su caso, está bien, como:

with relevant_ids as
  (
  select distinct(email_campaign_id) --as COLUMNNAME 
      from hubspot.email_events a
  where a.subject in ('subject1', 'subject2', 'subject3')
  )

select * 
  from hubspot.email_events a
where a.email_campaign_id in (SELECT COLUMNNAME from relevant_ids)
2
LONG 22 ene. 2018 a las 12:59

O simplemente únete a tu cte

  with relevant_ids as
  (
      select distinct(email_campaign_id) 
         from hubspot.email_events a
      where a.subject in ('subject1', 'subject2', 'subject3')
  )

select * 
  from hubspot.email_events a 
 join relevant_ids ri on ri.email_campaign_id = a.email_campaign_id
1
XXX 18 ene. 2018 a las 20:35

Debe utilizar una consulta SELECT dentro de IN:

with relevant_ids as (
    select distinct(email_campaign_id) 
    from hubspot.email_events a
    where
        a.subject in ('subject1', 'subject2', 'subject3')
)    
select * 
from hubspot.email_events a
where
    a.email_campaign_id in (SELECT email_campaign_id FROM relevent_ids);
1
Felix Pamittan 18 ene. 2018 a las 20:28