title: Select the count and value of a SQLAlchemy column using HAVING
body: <p>I want to select the count of all contacts with the same email address that have more than one duplicate. I can't get this query working in SQLAlchey with PostgreSQL.</p>
  
  <pre class="lang-sql prettyprint-override"><code>SELECT count(*), email FROM contact group by email having count(*) &gt; 1
  </code></pre>
  
  <p>I tried this:</p>
  
  <pre><code>all_records = db.session.query(Contact).options(
      load_only('email')).group_by(Contact.email).having(
      func.count('*') &gt; 1).all()
  </code></pre>
  
  
  
  <pre><code>sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "contact.id" must appear in the GROUP BY clause or be used in an aggregate function
  LINE 1: SELECT contact.id AS contact_id, contact.email AS contact_em...
             ^
  [SQL: 'SELECT contact.id AS contact_id, contact.email AS contact_email \nFROM contact GROUP BY contact.email \nHAVING count(%(count_1)s) &gt; %(count_2)s'] [parameters: {'count_1': '*', 'count_2': 1}]
  </code></pre>
  
  <p>And I tried this:</p>
  
  <pre><code>all_records = db.session.query(func.count(Contact.id)).options(
      load_only('email')).group_by(Contact.email).having(
      func.count('*') &gt; 1).all()
  </code></pre>
  
  
  
  <pre><code>sqlalchemy.exc.ArgumentError
  sqlalchemy.exc.ArgumentError: Wildcard loader can only be used with exactly one entity.  Use Load(ent) to specify specific entities.
  </code></pre>
  
  <p>It works correctly if I execute raw SQL:</p>
  
  <pre><code>all_records = db.session.execute(
      "SELECT count(*), email FROM contact group by email"
      " having count(*) &gt; 1").fetchall()
  </code></pre>
  
  <p>I'm using Flask-SQLAlchemy, but here's a minimal SQLAlchemy setup to demonstrate the issue:</p>
  
  <pre><code>import sqlalchemy as sa
  from sqlalchemy import orm
  from sqlalchemy.ext.declarative import declarative_base
  
  Base = declarative_base()
  
  class Contact(Base):
      __tablename__ = 'contact'
      id = sa.Column(sa.Integer, primary_key=True)
      email = sa.Column(sa.String)
  
  engine = sa.create_engine('postgresql:///example', echo=True)
  Base.metadata.create_all(engine)
  session = orm.Session(engine)
  session.add_all((
      Contact(email='a@example.com'),
      Contact(email='b@example.com'),
      Contact(email='a@example.com'),
      Contact(email='c@example.com'),
      Contact(email='a@example.com'),
  ))
  session.commit()
  
  # first failed query
  all_records = session.query(Contact).options(
      orm.load_only('email')).group_by(Contact.email).having(
      sa.func.count('*') &gt; 1).all()
  
  # second failed query
  all_records = db.session.query(sa.func.count(Contact.id)).options(
      orm.load_only('email')).group_by(Contact.email).having(
      sa.func.count('*') &gt; 1).all()
  </code></pre>
  
  <p>With the sample data, I expect to get one result row, <code>3, a@example.com</code>.</p>