3

I am trying to do something like this:

x = db_session.query(
    Candidate,
    func.count(case([(Jobs.interview_type == 'PHONE_SCREEN' and Jobs.interview_type == 'INCLINED' , 1)])),
    func.count(case([(Jobs.interview_type == 'PHONE_SCREEN' and Jobs.interview_type == 'NOT_INCLINED', 1)])),
    func.count(case([(Jobs.interview_type == 'IN_HOUSE', 1)])),
    func.count(case([(Jobs.interview_type == 'EVALUATION', 1)]))
    ).\
    join(Jobs, Jobs.candidate_id == Candidate.candidate_id).\
    filter(Candidate.candidate_id == '6236738').\
    first()

However its not picking up the second condition in case. Is this possible?

I got it working with and_ but its not giving the right answer

func.count(case([(and_(Jobs.interview_type == 'PHONE_SCREEN', Jobs.interview_type == 'INCLINED'), 1)])),

should return 2, but its returning 0

Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
Morgan Allen
  • 3,291
  • 8
  • 62
  • 86

1 Answers1

3

You need to use sqlalchemy.and_ instead of the and operator:

and_(Jobs.interview_type == 'PHONE_SCREEN',
     Jobs.interview_type == 'INCLINED')
Stephen Fuhry
  • 12,624
  • 6
  • 56
  • 55
  • Thats right! I'm stuck trying to put everything together...my syntax is off. Can you include `func.count(case[(...)])` with that too? – Morgan Allen Apr 18 '19 at 15:30
  • I got it working, but its not returning the desired result. I put updated solution. can you take a look? – Morgan Allen Apr 18 '19 at 15:34
  • One thing to try is `distinct(func.count(case()))`, but I'd want to look at the SQL that sqlalchemy generates to debug it further. – Stephen Fuhry Apr 19 '19 at 13:31
  • @StephenFuhry Hi, how to use `and_` with more than 2 values ? https://stackoverflow.com/questions/67496386/sqlalchemy-case-with-multiple-conditions-and-more-than-two-values – Elsa May 12 '21 at 02:50