0

If I have a table like this in BigQuery

id success ------------- 01 true 01 true 02 false 02 true 

I would like to end up with this:

id true false -------------------- 01 2 0 02 1 1 

I've got this but I wondered if there was a more elegant way to do it?

SELECT t1.id, ( SELECT count(*) FROM `my_table` t2 WHERE t2.success = true and t2.id = t1.id ) as trueCount, ( SELECT count(*) FROM `my_table` t3 WHERE t3.success = false and t3.id = t1.id ) as falseCount FROM `my_table` t1 GROUP BY id 
2
  • 1
    I think that's best what you can get. But... ID usually is primary key and must be unique. I hope it's just for demo Commented Mar 24, 2022 at 14:50
  • 1
    which database are you using Commented Mar 24, 2022 at 14:53

3 Answers 3

5

Consider conditional aggregation which should work on almost all databases:

SELECT t.id, SUM(CASE WHEN t.success = true THEN 1 ELSE 0 END) AS trueCount, SUM(CASE WHEN t.success = false THEN 1 ELSE 0 END) AS falseCount FROM `my_table` t GROUP BY t.id 
Sign up to request clarification or add additional context in comments.

4 Comments

where come t2 and t3 from, this query makes no sense, besides without nknowig the rdms...
@nbk...whoops! Fixed. Again, this should work on most RDBMS's that support CASE.
that is better, but still the question lacks vital detail and should be closed
@nbk Have updated the title and question text to mention that I'm using BigQuery. t2 and t3 are table aliases.
0

You can try to use condition aggregate function instead of the subquery.

SELECT id, COUNT(CASE WHEN success = true THEN 1 END) trueCount, COUNT(CASE WHEN success = false THEN 1 END) falseCount FROM T GROUP BY id 

Comments

0

consider below approach for BigQuery

select * from your_table pivot (count(*) for success in (true, false)) 

if applied to sample data in your question - output is

enter image description here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.