Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple named windows in a postgres query

The postgres docs specify a window definition clause thus:

[ WINDOW window_name AS ( window_definition ) [, ...] ]

The [,...] specifies that multiple windows are possible. I find nothing else in the docs to confirm or deny it's possible. How do I make this work?

In this query, I can use either window clause on its own but I can't use both even though the syntax follows the spec:

select q.*
, min(value) over w_id as min_id_val
--, min(value) over w_kind as min_kind_val
from (
    select 1 as id, 1 as kind, 3.0 as value
    union select 1, 2, 1.0
    union select 2, 1, 2.0
    union select 2, 2, 0.5
) as q
window w_id as (partition by id)
-- , 
-- window w_kind as (partition by kind)

I can get the technical effect by not using window definitions, but that gets tiresome for a complex query where windows are re-used:

select q.*
, min(value) over (partition by id) as min_id_val
, min(value) over (partition by kind) as min_kind_val
from (
    select 1 as id, 1 as kind, 3.0 as value
    union select 1, 2, 1.0
    union select 2, 1, 2.0
    union select 2, 2, 0.5
) as q
like image 205
Michael Grazebrook Avatar asked May 17 '26 16:05

Michael Grazebrook


1 Answers

Don't repeat the window keyword:

select q.*, 
       min(value) over w_id as min_id_val, 
       min(value) over w_kind as min_kind_val
from (
  values 
   (1,1,3.0),
   (1, 2, 1.0),
   (2, 1, 2.0),
   (2, 2, 0.5)
) as q(id,kind,value)
window w_id as (partition by id), 
       w_kind as (partition by kind)

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!