Rails SQL -запросы разговор

SmsMessage.where(
        sms_campaign_id: sms_campaign_ids
      ).select(
        "sum(CASE WHEN sms_messages.status = 1 THEN 1 ELSE 0 END) as enqueued_count",
        "sum(CASE WHEN sms_messages.status = 2 THEN 1 ELSE 0 END) as delivered_count",
        "sum(CASE WHEN sms_messages.status = 3 THEN 1 ELSE 0 END) as replies_count",
        "sum(CASE WHEN sms_messages.status = 4 THEN 1 ELSE 0 END) as failed_count",
        "sum(CASE WHEN sms_messages.status IN (1,2,4) THEN 1 ELSE 0 END) as sends_count",
        "count(id) as total_messages_count"
      )
Blue-eyed Boar