Re: FIRST_VALUE argument must appear in group by?

From: Guyren Howe <guyren(at)gmail(dot)com>
To: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: FIRST_VALUE argument must appear in group by?
Date: 2016-05-17 17:36:03
Message-ID: 90607C87-5A2A-4F74-9C8D-DCAE5BB38484@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I am trying to use a window function, but it's not working. The subquery is effectively aggregating.

> On May 17, 2016, at 6:18 , David G. Johnston <david(dot)g(dot)johnston(at)gmail(dot)com> wrote:
>
> On Tue, May 17, 2016 at 12:04 AM, Guyren Howe <guyren(at)gmail(dot)com <mailto:guyren(at)gmail(dot)com>> wrote:
> On May 16, 2016, at 20:48 , David G. Johnston <david(dot)g(dot)johnston(at)gmail(dot)com <mailto:david(dot)g(dot)johnston(at)gmail(dot)com>> wrote:
>>
>> On Monday, May 16, 2016, Guyren Howe <guyren(at)gmail(dot)com <mailto:guyren(at)gmail(dot)com>> wrote:
>> I have this SELECT clause as part of a larger query:
>> FIRST_VALUE(drs.id) OVER (PARTITION BY drs.order_ID ORDER BY drs.position ASC) AS current_drs_id
>> Seems reasonable to me: group and sort the fields in this table and give me the first value.
>>
>> But I get "column "drs.id <http://drs.id/>" must appear in the GROUP BY clause or be used in an aggregate function".
>>
>> Huh?
>>
>> The larger query would help…
>
> SELECT
> o.id,
> os.status AS status,
> o.status_updated_at,
> o.should_hold_at_airlines,
> (SELECT drs2.id FROM delivery_route_segments drs2 WHERE drs2.order_id = o.id AND NOT drs2.completed ORDER BY drs2.position LIMIT 1) AS current_drs_id,
>
>
> FROM
> orders o JOIN
> order_statuses os ON (o.status = os.id) JOIN
> delivery_route_segments drs ON (drs.order_id = o.id) JOIN
> pick_up_addresses pua ON (pua.order_id = o.id)
> GROUP BY
> o.id, os.status
> I would prefer to do the subquery as a window function, both because that is cleaner to read and also because I believe it is likely to be more efficient.
>
>
> ​This query is non-functional. It has a GROUP BY without any aggregate functions and not all of the selected columns are in the group by.
>
> David J.
>

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Guyren Howe 2016-05-17 17:38:32 Re: Thoughts on "Love Your Database"
Previous Message Karsten Hilbert 2016-05-17 16:42:32 Re: Ascii Elephant for text based protocols - Final