我的数据如下:
product | month | purchased
a jan online
a jan instore
b jan online
c jan instore
我想要做的是确定在同一个月内在同一个结果集中购买产品的方式如下:
product | month | purchased | method
a jan online online-instore
a jan instore online-instore
b jan online online
c jan instore instore
我想知道是否有办法编写可以执行此操作的窗口查询,而不是编写单独的查询,然后将其连接回结果集。
答案 0 :(得分:0)
MIN/MAX
个窗口函数:
SELECT product, month, purchased,
CASE max( purchased ) OVER (partition by product, month )
WHEN min( purchased ) OVER (partition by product, month )
THEN min( purchased ) OVER (partition by product, month )
ELSE max( purchased ) OVER (partition by product, month )
|| '-' ||
min( purchased ) OVER (partition by product, month )
END As method
FROM Table
答案 1 :(得分:0)
select
product, month,
array_agg(purchased) over (partition by product, month) as method
from
your_table
group by
product, month, purchased;
如果您想要method1-method2-...
结果,请将array_agg(purchased)
更改为string_agg(purchased, '-')