【问题标题】:Requiring a super fast postgres SQL query需要超快速的 postgres SQL 查询
【发布时间】:2020-01-30 06:18:24
【问题描述】:

我想为 Postgresql 解决一个查询

我首先生成一系列日期:

with t as(
SELECT 
    uuid_generate_v4() as generated_id,
    date_trunc('day', dd):: date as generated_date,
    '75e46430-2f19-c9fc-5c8a-1aeb423a7c84'::uuid as account_id
FROM generate_series
        ( '2019-04-01'::timestamp 
        , '2019-05-01'::timestamp
        , '1 day'::interval) dd
)

然后我有另一个表 [Transactions],如下所示:

account_id | order_date | debit_amount | credit_amount

事务表每天可以有数千个给定帐户的条目。每笔交易要么是借方,要么是贷方,即,如果是贷方,贷方列中将有一个值,而借方列对于特定交易将为空。

我正在尝试设计一个超快查询,它会给出以下结果:

generated_id | account_id | order_date | sum(total_of debits_for_order_date) | sumtotal_of_credits_for_order_date)

地点:

order_date = generated_date 
t.account_id = transations.account_id

如果特定日期的借方或贷方为空,我仍然需要返回一个空行。

例如

generated_id  |  account_id  |  generated_date |  debit  |  credit
fjsda-klf...     75e46430...      2019-01-01      1.50      null
gassd-fsd...     75e46430...      2019-01-02      null      null

【问题讨论】:

  • 你的 generated_date 在哪里?
  • CTE 中的account_id 值与预期结果不匹配。确定是同一列吗?
  • @ϻᴇᴛᴀʟ 我刚刚更新了。结果应该显示 generated_date 而不是 order_date。但订单日期必须与查询中的 generated_date 匹配。
  • @TheImpaler 我已经编辑了帖子以反映。干杯
  • 你可以试试explain analyze select uuid_generate_v4() from generate_series(1,1e5)explain analyze select gen_random_uuid() from generate_series(1,1e5)。第一个在我的笔记本电脑上需要 36 ,第二个需要 60 毫秒

标签: sql postgresql


【解决方案1】:

查询。

with t as(
SELECT 
    uuid_generate_v4() as generated_id,
    date_trunc('day', dd):: date as generated_date,
    '75e46430-2f19-c9fc-5c8a-1aeb423a7c84'::uuid as account_id
FROM generate_series
        ( '2019-04-01'::timestamp 
        , '2019-05-01'::timestamp
        , '1 day'::interval) dd
), tdata as (
  select a.account_id, a.order_date, sum(debit_amount) as debit, sum(credit_amount) as credit
from transations a
where exists (
  select 1 from t where t.generated_date = a.order_date and t.account_id = a.account_id
)
select t.generated_id, t.account_id, t.generated_date, m.debit, m.credit
from t left join tdata m on (t.generated_date = m.order_date and t.account_id = m.account_id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-08
    • 2022-11-29
    • 2013-08-31
    • 2011-07-16
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2022-09-17
    相关资源
    最近更新 更多