0

Any suggestions how to prevent this behaviour of group by that it is skipping dates in the results instead of returning 0.

I have written the following query to group transactions by date but of no transactions were found, that date got skipped in the result


   const dailyTransactions = await this.transactionsRepo
      .createQueryBuilder('transaction')
      .leftJoinAndSelect('transaction.currency', 'currency')
      .select("to_char(transaction.created_at, 'YYYY-MM-DD')", 'date')
      .addSelect(
      `
        SUM(CASE WHEN currency.currency_code = '${CAD}' THEN amount ELSE 0 END) AS CAD,
        SUM(CASE WHEN currency.currency_code = '${GBP}' THEN amount ELSE 0 END) AS GBP
        `,
      )
      .where('transaction.created_at >= :daysAgo', { daysAgo })
      .groupBy('date')
      .orderBy('date', 'DESC')
      .getRawMany();

These are the results of last 10 days, here 11th and 8th are being skipped Any suggestion how to prevent this behaviour

"dailyTransactions": [
    {
        "date": "2023-02-16",
        "cad": "70.00",
        "gbp": "70.00"
    },
    {
        "date": "2023-02-15",
        "cad": "0",
        "gbp": "60.00"
    },
    {
        "date": "2023-02-14",
        "cad": "198.00",
        "gbp": "0"
    },
    {
        "date": "2023-02-13",
        "cad": "175.00",
        "gbp": "0"
    },
    {
        "date": "2023-02-12",
        "cad": "75.00",
        "gbp": "0"
    },
    {
        "date": "2023-02-10",
        "cad": "60.00",
        "gbp": "0"
    },
    {
        "date": "2023-02-09",
        "cad": "68.00",
        "gbp": "0"
    },
    {
        "date": "2023-02-07",
        "cad": "65.00",
        "gbp": "0"
    }
]
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • I can't give a complete solution, since I don't know the tool you are using. But in general you need to do an outer join with a list of dates. This describes how you can achieve this with Postgres https://stackoverflow.com/a/11391987/66686 – Jens Schauder Feb 16 '23 at 11:37

0 Answers0