Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return column based on underlying rows in aggregate query

Consider this table:

 comment_id | vote | user_id 
------------+------+---------
      79507 |    1 |  351501
      79507 |    2 |  533594
      79544 |    1 |  648703
      79544 |    1 |  533594
      79544 |    2 |  790789
      79545 |    1 |  351501

This aggregate query returns the sum of the vote column for every comment_id:

SELECT comment_id, SUM(vote_up) 
FROM votes 
GROUP BY comment_id 
ORDER BY comment_id;

 comment_id | sum 
------------+-----
      79507 |   3
      79544 |   4
      79545 |   1

However, I would like an additional column to be returned if any of the underlying grouped rows satisfy a condition. In this case, the voted column should be true if and only if any of the aggregated rows has a given user_id (user_id 351501 in this example):

 comment_id | sum | voted
------------+-----+-------
      79507 |   3 |     t
      79544 |   4 |     f
      79545 |   1 |     t

I see a possible solution with by JOINing the table on itself, but that seems like a hack and seems highly inefficient. I came across window functions, not sure if they apply to this problem.

like image 248
David Chouinard Avatar asked May 21 '26 05:05

David Chouinard


1 Answers

Use the aggregate function bool_or():

SELECT comment_id, SUM(vote_up) AS sume_vote
      ,bool_or(user_id = 351501) AS voted
FROM   votes
GROUP  BY 1
ORDER  BY 1;
like image 132
Erwin Brandstetter Avatar answered May 22 '26 17:05

Erwin Brandstetter