0

I am trying to write a SQL query where I want to count the number of existence of Q1, Q2, Q3 and Q4 in Quarter. I have tried looking the previous questions but they weren't much clear. Here's my code:

SELECT  
COUNT(Quarter CASE WHEN Quarter = 'Q1') 
COUNT(Quarter CASE WHEN Quarter = 'Q2') 
COUNT(Quarter CASE WHEN Quarter = 'Q3') 
COUNT(Quarter CASE WHEN Quarter = 'Q4') 
FROM office.office;

What am I doing wrong?

1 Answer 1

2

You want conditional aggregation here. Here is a terse way of doing this on MySQL by summing boolean expressions:

SELECT  
    SUM(Quarter = 'Q1') q1_total,
    SUM(Quarter = 'Q2') q2_total,
    SUM(Quarter = 'Q3') q3_total,
    SUM(Quarter = 'Q4') q4_total
FROM office.office;

If you wanted to use COUNT, here is the correct syntax for that:

COUNT(CASE WHEN Quarter = 'Q1' THEN 1 END) q1_total  -- and so on
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.