SQL:按月索引划分每日数据

时间:2016-10-26 17:49:26

标签: sql postgresql date

我有每日交易数据,这是此查询的产物:

SELECT  transaction_date  ,
    Merchant,
    Amount

into transaction.table
FROM    source.table
WHERE (DESCRIPTION iLIKE '%Criteria%')

字段transaction_date的格式为DATE(yyyy-MM-dd)。

我想要做的是在transaction.table中获取每一行/事务,并将Amount除以一个名为Calendar的单独表中包含的与其RESPECTIVE月相关的值(这是关键字)。

从同一个source.table中查询名为Calendar的单独表格,如下所示:

select month,count(*) as distinct_month
into source.Calendar
from
(
select Population, to_char(optimized_transaction_date, 'YYYY-MM') as month
FROM source.table
group by Population, to_char(optimized_transaction_date, 'YYYY-MM')
)
group by month

我的目标是获得每天的价值:金额/不同_月。

关键部分是将第一个查询中的每日数据(transaction_date)与第二个查询(月份)中的月度数据进行匹配。

请注意,第二个查询的月份是varchar,而第一个查询中的transact_date是DATE。

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

SELECT transaction_date, Merchant, Amount, newval
FROM (SELECT transaction_date, Merchant, Amount, Description,
             (Amount / count(distinct population) over (partition by to_char(transaction_date, 'YYYY-MM')
             ) as newval
      FROM source.table
     ) t
WHERE DESCRIPTION iLIKE '%Criteria%';

您只需要子查询,因为总计是根据所有数据计算的,没有过滤条件。

编辑:

哎呀,我忘了Postgres不支持COUNT(DISTINCT)作为窗口函数。所以:

SELECT transaction_date, Merchant, Amount, newval
FROM (SELECT t.*,
             (Amount / SUM( (seqnum = 1)::int) OVER (partition by to_char(transaction_date, 'YYYY-MM') )
             ) as newval
      FROM (SELECT t.*,
                   ROW_NUMBER() OVER (PARTITION BY partition by to_char(transaction_date, 'YYYY-MM'), population ORDER BY population) as seqnum
            FROM source.table t
           ) t
     ) t
WHERE DESCRIPTION iLIKE '%Criteria%';