Flowframe / laravel-trend

Generate trends for your models. Easily generate charts or reports.
MIT License
607 stars 64 forks source link

Invalid column reference when trying to fetch distinct column #21

Closed otilor closed 1 year ago

otilor commented 1 year ago

Problem description

When trying to retrieve unique attendees of an event. I'm using this query:

Attendee::query()->distinct('user_id')

It works on its own but when using it in this chart widget;

Trend::query(Attendee::query()->distinct('user_id'))
            ->between(
                start: now()->setDate(2021, 1, 1),
                end: now(),
            )
            ->perMonth()
            ->count();

I get this error:

SQLSTATE[42P10]: Invalid column reference: 7 ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: select distinct on ("user_id") ^ (SQL: select distinct on ("user_id") to_char(created_at, 'YYYY-MM') as date, count(*) as aggregate from "attendees" where "created_at" between 2021-01-01 16:43:04 and 2022-10-14 16:43:04 group by "date" order by "date" asc)
Larsklopstra commented 1 year ago

Closing stale issue

vpuentem commented 9 months ago

Did you manage to get it? I'm trying to do something similar with no results :/

otilor commented 9 months ago

Can't really remember. I think I did tho'. No longer have access to the codebase.

vpuentem commented 9 months ago

This works apparently, if you look at the aggregate() method used by the count(), sum(), etc. It uses the column name and the aggregate in a string, so you can pass different values depending on what you need

Trend::query(Attendee::query())
            ->between(
                start: now()->setDate(2021, 1, 1),
                end: now(),
            )
            ->perMonth()
            ->count('DISTINCT user_id');
otilor commented 8 months ago

Ok. Thank you.

MCKLtech commented 3 weeks ago

@vpuentem , thank you, this worked for me.