Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXISTS inside CASE inside AGGREGATE FUNCTION

I'm trying to do something similar to this:

SELECT SUM(
          CASE WHEN (<some_condition> 
                     AND EXISTS(SELECT 1 
                                FROM <tableA> as tA
                                WHERE tA.Id = tB.tAId and
                                <some_other_condition>
                               )
                    ) THEN 1 ELSE 0 END
          ) as <column_name>
FROM <tableB> as tB

I need to avoid the use of joins to achieve what I need, because I don't want to count/sum duplicates returned by the results I get through join clauses in this case. When I try to execute my query, I get the following error message:

"cannot perform an aggregate function on an expression containing an aggregate or a subquery"

I don't know what I am doing wrong.

Any help appreciated.

EDIT: I added a possible condition on the WHERE statement only to show I need to relate the columns of the outside table (tableB) with the inside table (tableA)

Here's an example of tableA and tableB and what happens when I JOIN both:

tableA:     tableB:          tableA JOIN tableB
Id          Id tAId Time     Id(A) Id(B) taId Time
 1           1    1    5        1     1     1    5
 2           2    2    6        2     2     2    6
 3           3    2   10        2     3     2   10
 4           4    3   11        3     4     3   11
 5           5    4   14        4     5     4   14
             6    4   13        4     6     4   13
             7    4   12        4     7     4   12   
             8    5   10        5     8     5   10

So, when I try to count/sum some property (i.e. tableA.Id) from tableA using the results of the JOIN operation as input, I end up counting duplicates. Here's why I can't use JOIN unless I can select DISTINCT elements. I liked the answer that shows this so I'm trying to implement that with no errors.

(Note: I really appreciate all the other answers since they show possible solutions that can fit my situation)

like image 930
Mari Faleiros Avatar asked Mar 25 '26 05:03

Mari Faleiros


1 Answers

SELECT SUM(
          CASE WHEN (<some_condition> 
                     AND tA.Id IS NOT NULL
                    ) THEN 1 ELSE 0 END
          ) as <column_name>
FROM <tableB> as tB
     JOIN (SELECT DISTINCT ta.Id
           FROM <tableA>) as tA ON tA.Id = tB.Id AND <some_other_condition>
like image 76
StanislavL Avatar answered Mar 27 '26 03:03

StanislavL