Search code examples
scalaslick

How to perform a multi sum with group by in Slick?


I have the following query in sql :

SELECT TASK_ID, TOTAL_WRITER_SUCCESS as WRITER_SUCCESSES, TOTAL_WRITER_ERRORS as WRITER_ERRORS,
SUM(if (SERVICE = 'Reader' AND  ERROR IS NOT NULL,1,0)) AS READER_ERRORS,
SUM(if (SERVICE = 'Reader' AND ERROR IS  NULL,1,0)) AS READER_SUCCESSES,
SUM(if (SERVICE = 'Writer' AND  ERROR IS NOT NULL AND (TOTAL_WRITER_SUCCESS IS NULL AND TOTAL_WRITER_ERRORS IS NULL),1,0)) AS WRITER_CURRENT_ERRORS
FROM TASK_EVENT_STATUS GROUP BY TASK_ID 

I am trying to express it in Slick.

I am managed to express one sum like this :

taskEventStatuses.groupBy(tes => tes.taskId).map {
      case (taskId, group)  => (taskId, group.map { tes =>
        Case If tes.error.isEmpty && tes.service === Service.Reader.asInstanceOf[Service] Then 1 Else 0
      }.sum) 

I didn't find a way to all the sums in Slick ?


Solution

  • This works for me :

    taskEventStatuses.groupBy(_.taskId).map {
      case (taskId, group)  =>
        (group.map( tes => Case If tes.error.isEmpty && tes.service === Service.Reader.asInstanceOf[Service] Then 1 Else 0).sum
          , group.map( tes => Case If tes.error.isDefined && tes.service === Service.Reader.asInstanceOf[Service] Then 1 Else 0).sum
          , group.map( tes => Case If tes.error.isDefined && tes.service === Service.Writer.asInstanceOf[Service] Then 1 Else 0).sum
        ,taskId)
      }