选择每月重复的行

时间:2014-08-26 15:33:44

标签: sql ruby-on-rails postgresql

我想先解决一下简单的任务。

我有transactions表。

|  name  |entity_id| amount |    date    |
|--------|---------|--------|------------|
| Github |    1    |  4.80  | 01/01/2014 |
| itunes |    2    |  2.80  | 22/01/2014 |
| Github |    1    |  4.80  | 01/02/2014 |
|  Foods |    3    |  24.80 | 01/02/2014 |
| amazon |    4    |  14.20 | 01/03/2014 |
| amazon |    4    |  14.20 | 01/04/2014 |

我必须选择在同一天每月重复的行,entity_id的数量相同。(订阅)。谢谢你的帮助

2 个答案:

答案 0 :(得分:1)

如果您的date列已创建为date类型,

  • 您可以使用递归CTE来收集续集
  • 之后,使用distinct on
  • 删除重复的行
  • (并且应该重命名该列,因为它是SQL中的保留名称)

with recursive recurring as (
    select name, entity_id, amount, date as first_date, date as last_date, 0 as lvl
    from transactions
  union all
    select r.name, r.entity_id, r.amount, r.first_date, t.date, r.lvl + 1
    from recurring r
    join transactions t
      on row(t.name, t.entity_id, t.amount, t.date - interval '1' month)
         = row(r.name, r.entity_id, r.amount, r.last_date)
)
select distinct on (name, entity_id, amount) *
from recurring
order by name, entity_id, amount, lvl desc

SQLFiddle

答案 1 :(得分:0)

按天分组,样本:

select entity_id, amount, max(date), min(date), count(*)
from transactions
group by entity_id, amount, date_part('day', date)