Good day. I make a request in Doctrine.

... ->addSelect('(CASE WHEN c.type = 1 THEN ( SUM(c.amountMain) AND COUNT(c.id) ) ELSE 0 END)') 

I want to return SUM (c.amountMain) and COUNT (c.id) when fulfilling the condition

Help please issue a request.

  • If this is SQL, then you want something strange. What does “SUM” and “COUNT” mean that it should return to you? - Mike
  • @Mike needs to return the amount and the number of summed elements. If I do not add COUNT, then everything works fine. But I need both. - Vladislav
  • One expression - one column. Two results are needed - make 2 expressions, i.e. in SQL, it would look (case ... sum()), (case ... count()) . And in general a little strange condition. Do you have a group by request in the c.type column? Just because you have written c.type in case should be checked for each line, i.e. before grouping, and sum () and count () will take many lines into account, i.e. After grouping - Mike
  • @Mike thought that it would not be possible to simplify the task. No, I did not use group by, it was necessary that the condition was checked for each row. Thanks for the help. I think my question turned out to be useless for society and it should be removed altogether. - Vladislav
  • For each line, move the condition check inside the sum(case ... then amountMain else 0 end) function sum(case ... then amountMain else 0 end) - Mike

1 answer 1

In general, actions need to be carried out separately. And you do not need to use COUNT () in this case, since all the results will be counted. SUM () should be used instead.

 ->addSelect('SUM((CASE WHEN c.type = 1 THEN c.amountMain ELSE 0 END) as sum') ->addSelect('SUM((CASE WHEN c.type = 1 THEN 1 ELSE 0 END) as count')