0

I want to write something like this:

  select 
    "id", 
    "plant", 
    "product", 
    "uom", 
    count(*) as transactions_count,
    avg(("invoice_price" / "quantity")) filter (where ("date" == max(date))  as "LAST_GUIDANCE", -- I want group by date only for this
  from "transactions"
  group by 
    "id", 
    "plant", 
    "product", 
    "uom"

Where I want to count last guidance but only for rows with last date.

Problem is that I cannot add "date" to group by, because I want this grouping only for last_guidance.. It is possible to write it somehow easily in Postgres (use "over" for ex.) or I have to create too separated queries and then join them?

Thanks for answers

  • Does this answer your question? [Get values from first and last row per group](https://stackoverflow.com/questions/25170215/get-values-from-first-and-last-row-per-group) – a'r May 27 '20 at 10:12

1 Answers1

1

This is not allowed. The error message is pretty clear:

ERROR: aggregate functions are not allowed in FILTER LINE 1: select count(*) filter (where x = max(x))

Nor are window functions allowed.

You can use a subquery to calculate the maximum date:

select id, plan, product, uom,
       count(*) as transactions_count,
       avg(invoice_price / quantity) filter (where date = max_date)  as LAST_GUIDANCE
from (select t.*, 
             max(date) over (partition by id, plan, product, uom) as max_date
      from transactions t
     ) t
group by id, plan, product, uom;

Note that I removed the double quotes. Don't escape column names. That just makes queries harder to write and read.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thank for your answer :) And sorry for double quotes - original query is more complicated with upper case column names.. I did simplification just for ask here (this is only inner query of complicated query).. – Radek Chromík May 27 '20 at 11:41