我遇到了一个问题,需要让生成的内容“好看”,高效,易读。不幸的是,它缺少这两个属性。
给定一个具有 date,transaction_type,username
和 credits
的表,我想要生成一个视图,概括如下字段:date_from, date_next, username, credits_total, credits_total
解释:
- date_from 和 date_next 是每月的第一天和下一个月的第一天。 (例如 2022-06-01 和 2022-07-01)
- username 被分组,所以每对 date_from/date_next 只有一个相同的 username
- credits_total 是 transaction='charge' 时 credit_change 的总和
- credits_left 是 credits_total - sum(credits_change where transaction_type = 'usage')
我已经确定了多个问题,并且已经部分解决了它们:
- 使用
date_trunc('month', date)
和 `date_trunc('month', date) + interval '1 month'' 很容易得到 date_from/_next - 通过 group by 可以对 username/dates 进行分组
- 制作 credits_total 没有重复很难。那么子查询是唯一的解决方案吗?
- credits_left 几乎相同,但是与其他 transaction_type 相关,并从 credits_total 中减去。如何重用 credits_total?
我想到了以下内容(并且非常不满意):
原始表:
create table usage -- simplified
(
datetime timestamp default now() not null,
transaction_type varchar(16) not null,
user varchar(128) not null,
credits_change int not null,
);
我的视图代码:
CREATE MATERIALIZED VIEW token_usage
AS
SELECT
-- trivial:
user,
date_trunc('month', datetime) as date_from,
date_trunc('month', datetime) + interval '1 month' as date_next,
-- sum of credits_change with requirement + duplication
( -- see here. first time
SELECT sum(credits_change)
FROM usage
WHERE transaction_type = 'charge'
AND datetime BETWEEN date_trunc('month', datetime) AND date_trunc('month', datetime) + interval '1 month'
) as credits_total,
-- sum of credits change minus other sum and more duplication
( -- see here. using the same again
SELECT sum(credits_change)
FROM usage
WHERE transaction_type = 'charge'
AND datetime BETWEEN date_trunc('month', datetime) AND date_trunc('month', datetime) + interval '1 month'
) - ( -- see here. using the same again, but with different transaction_type
SELECT sum(credits_change)
FROM usage
WHERE transaction_type = 'usage'
AND datetime BETWEEN date_trunc('month', datetime) AND date_trunc('month', datetime) + interval '1 month'
) as credits_left
FROM usage
GROUP BY user_name, datetime, datetime_next_start
WITH DATA;
说实话,看起来我只是缺少一些postgresql工具,以使它更好。
谢谢你的帮助 :)