我正在尝试更改下面查询的计数DISTINCT部分,因为当前查询返回不支持WINDOW定义。使用PostgreSQL进行此计算的最无缝方法是什么?谢谢。
SELECT transaction_date, brand, Description, Amount, newval
into temp.table
FROM (SELECT transaction_date, brand, Description, Amount,
(Amount / count(DISTINCT unique_mem_id) over (partition by to_char(transaction_date, 'YYYY-MM'),brand
)) as newval
FROM source.table
)
WHERE DESCRIPTION iLIKE '%Criteria%';
答案 0 :(得分:1)
由于用例,分割代码似乎更好。
根据以下查询创建表 month_brand :
select to_char(transaction_date, 'YYYY-MM') as yyyymm
,brand
,count (distinct unique_mem_id) as count_distinct_unique_mem_id
from source.table
group by yyyymm
,brand
;
将 month_brand 加入源表:
select t.transaction_date, t.brand, t.Description, t.Amount, t.Amount / m.count_distinct_unique_mem_id as newval
from source.table as t
join month_brand as m
on m.yyyymm = to_char(t.transaction_date, 'YYYY-MM')
where t.description ilike '%Criteria%'
;
而不是count(distinct ...)
,2阶段解决方案:
select *
into temp.table
from (SELECT transaction_date, brand, Description, Amount,
(Amount / count(case rn when 1 then unique_mem_id end) over (partition by to_char(transaction_date, 'YYYY-MM'),brand)) as newval
FROM (SELECT transaction_date, brand, Description, Amount,unique_mem_id
row_numner () over (partition by to_char(transaction_date, 'YYYY-MM'),brand,unique_mem_id) as rn
FROM source.table
)
)
WHERE DESCRIPTION iLIKE '%Criteria%'
;