title: sequelize distinct ,count and grouping
body: <p>I have a database of uploaded files , each file can have one of 4 stages; recieved, converting, done and failed. need to bring a count of each stage for each. The date is stored in the &quot;ReceivedAt&quot; column in ms.
  this is my code. it works, but it takes a long time to get all the information out.</p>
  <pre><code>const dates = await Job.aggregate(&quot;recievedAt&quot;, &quot;DISTINCT&quot;, { plain: false });
    const dates_sorted = dates.sort((a, b) =&gt; a - b);
  
    const rev_date = dates_sorted.reverse();
    let day;
  
    const summery_by_date = [];
    try {
      await Promise.all(
        rev_date.map(async (date) =&gt; {
          const string_d = new Date(Number(date.DISTINCT)).toDateString();
          if (!(day === string_d)) {
            day = string_d;
  
        const d_num = new Date(Number(date.DISTINCT));
        const date_midnight = d_num.toISOString().split(&quot;T&quot;)[0];
        const beaging_date = Number(new Date(date_midnight).getTime());
        const end_date = Number(beaging_date + 86400000);
  
        const total = await Job.count({
          where: {
            recievedAt: {
              [Op.between]: [beaging_date, end_date],
            },
          },
        });
        const failed = await Job.count({
          where: {
            [Op.and]: [
              {
                recievedAt: {
                  [Op.between]: [beaging_date, end_date],
                },
              },
              { stage: &quot;failed&quot; },
            ],
          },
        });
        const converting = await Job.count({
          where: {
            [Op.and]: [
              {
                recievedAt: {
                  [Op.between]: [beaging_date, end_date],
                },
              },
              { stage: &quot;converting&quot; },
            ],
          },
        });
        const recieved = await Job.count({
          where: {
            [Op.and]: [
              {
                recievedAt: {
                  [Op.between]: [beaging_date, end_date],
                },
              },
              { stage: &quot;recieved&quot; },
            ],
          },
        });
        const done = await Job.count({
          where: {
            [Op.and]: [
              {
                recievedAt: {
                  [Op.between]: [beaging_date, end_date],
                },
              },
              { stage: &quot;done&quot; },
            ],
          },
        });
  
        summery_by_date.push({
          date: beaging_date,
          total: total,
          failed: failed,
          converting: converting,
          recieved: recieved,
          done: done,
        });`
  </code></pre>
  <p>thanks in advance</p>