【问题标题】:Postgres Rows Between Causing DuplicatesPostgres 行之间导致重复
【发布时间】:2018-09-23 05:35:06
【问题描述】:

我有一个简单的查询来计算当前行和前 11 行的值的总和。当行数大于 12 时它可以正常工作,但是当它小于 12 时,数据会被复制以填充缺失值。

总表:

ID|Report_Month| Total
1 |2018-08-01 |5
2 |2018-09-01 |25
3 |2018-10-01  |15

示例代码:

select distinct 
         ID,
         Report_Month,
         Total,
         sum(Total) over (partition by ID order by report_month rows between 11 preceding and current row) as Running_Total
from TOTALS_TABLE;

预期输出:

ID|Report_Month|Total|Running_Total
1 | 2018-08-01 | 5 | 5
2 | 2018-09-01 | 25 | 30
3 | 2018-10-01 | 15 | 45

实际输出:

1 | 2018-08-01 | 5 | 5
1 | 2018-08-01 | 5 | 10
1 | 2018-08-01 | 5 | 15
1 | 2018-08-01 | 5 | 20
2 | 2018-09-01 | 25 | 45
2 | 2018-09-01 | 25 | 70
2 | 2018-09-01 | 25 | 95
2 | 2018-09-01 | 25 | 120
3 | 2018-10-01 | 15 | 135
3 | 2018-10-01 | 15 | 150
3 | 2018-10-01 | 15 | 165
3 | 2018-10-01 | 15 | 180

任何帮助将不胜感激,我觉得我很接近可能错过了一些东西。

【问题讨论】:

  • 为什么里面有 DISTINCT?
  • 请编辑您的帖子,选择任何将受益于等宽字体预格式化样式的内容,然后按代码。哈顿上方的文本框。它将在每行的开头添加 4 个空格,这就是我们如何使代码块正确显示在 SO..
  • mysql、postgresql、tsql都是互斥的,你用的是哪个DBMS?
  • 我认为 Postgres 考虑到他是在这个主题中写的,其他标签可能只是为了引起相关专业人士的注意(请避免这样做),他们可以回答。 Sql 标签是一个更好的保护伞

标签: sql postgresql window-functions


【解决方案1】:

线索是select distinct。这不应该是必要的。如果基础表有重复项,您应该修复它。同时,您可以尝试调整查询。

我不确定正确的解决方法是什么。这里有两种可能性。

如果整行重复:

select ID, Report_Month, Total,
       sum(Total) over (partition by ID order by report_month rows between 11 preceding and current row) as Running_Total
from (select distinct tt.*
      from TOTALS_TABLE tt
     ) tt;

如果totals表中每个dy都有小计需要相加:

select ID, Report_Month,
       sum(Total) as month_total,
       sum(sum(Total)) over (partition by ID order by report_month rows between 11 preceding and current row) as Running_Total
from TOTALS_TABLE tt
group by id, Report_Month;

【讨论】:

  • 我还通过以下查询得到重复的行 ``` select , min(bound_ts1) over(partition by risk_model_name order by bound_ts1 rows unbounded before) start_date, max(bound_ts1) over(按 risk_model_name 分区 order by bound_ts1 rows unbounded before) last_date, dense_rank() over(order by risk_model_name rows unbounded prior) rnk, (submitted_ts1-quoted_ts1) tat_quote, (quoted_ts1-bound_ts1) tat_bound from (select distinct t1. from t1) t2; ``` 第一个解决方案解决了它,但我不知道为什么?
【解决方案2】:

您似乎想要一个对不同 ID 求和的查询,但您已将总和按 ID 分区,这意味着每次 ID 更改时您的运行总数都会重置(== 您发布的查询无法可以产生你发布的结果,即使 Postgres 自发地发明行来提供一些总结)。删除分区

https://www.db-fiddle.com/#&togetherjs=fw7TIVul3H

我没有遇到重复行问题,我不明白为什么添加分析会导致它。我认为您的源表或查询确实有重复的行(我认为您使用 distinct 试图删除它们)并且分析工作正常。做一个

Select * from totals_table 

并检查您的数据是否正常。如果它有重复的行,您不能以您的方式使用 distinct 删除它们,因为 distinct 会考虑运行总计的结果(并且它使每一行都是唯一的)。最好从源头解决重复问题,而不是稍后尝试将它们区分开来,但是如果您打算这样做,则必须在内部查询中进行区分,并在外部查询中进行总计

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 2016-11-05
    • 2021-02-25
    • 1970-01-01
    • 2019-07-29
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多