【问题标题】:PostgreSQL counting from a special datePostgreSQL 从一个特殊的日期开始计数
【发布时间】:2021-04-24 06:38:56
【问题描述】:

我有以下代码,

SELECT      
    years_month_count.day_date,
    years_month_count.year_date,
    years_month_count.month_date,
    years_month_count.no_of_customers_day,
    sum(years_month_count.no_of_customers_day) OVER (PARTITION BY year_date ORDER BY day_date) AS no_of_customers_ytd
FROM (
    SELECT 
        DATE(date) as day_date,
        DATE_PART('year',date) as year_date,
        DATE_PART('month',date) as month_date,
        count(prepare_first_buyer.person_id) as no_of_customers_day
    FROM (
        SELECT 
            DATE(bestelldatum),
            person_id,
            ROW_NUMBER() OVER (PARTITION BY person_id ORDER BY person_id)
        FROM ani.bestellung
    ) prepare_first_buyer
    WHERE row_number=1
    GROUP BY DATE(date), DATE_PART('year',date),DATE_PART('month',date)
    ORDER BY DATE(date), DATE_PART('year',date),DATE_PART('month',date)
) years_month_count

输出如下所示:

day_date year_date month_date no_of_customers_day no_of_Customers_ytd
2017-04-04 2017 4 6 6
2017-04-05 2017 4 4 10
... ... ... ... ...
... ... ... ... ...

等等。

no_of_customers_ytd 将在每个新年伊始(1 月 1 日)设置为零。 但我需要在一个特殊的日期将其设置为零,比如每年的 1.June。 所以我需要每年从 1.June 到 30.March 之间的所有事情的总和。

感谢您的帮助。

【问题讨论】:

  • 请以文本形式提供表格描述 (DDL) 和示例数据 - 无图像(或 fiddle)以及该数据的预期输出。

标签: sql postgresql date sum


【解决方案1】:

step-by-step demo:db<>fiddle

SELECT
    *,
    SUM(value) OVER (PARTITION BY                             -- 4
        date_part('year',                                     -- 3
            the_date - interval '5 months'                    -- 2
        )     
    )
FROM t
WHERE date_part('month', the_date)::int NOT BETWEEN 4 AND 5   -- 1
  1. 过滤所有不需要的日期。在您的示例中,所有日期都带有月份 45
  2. 将日期范围从年初开始。在您的示例中,您必须将:year-06-01 转换为 year-01-01,因此您需要减去 5 months。由于您的日期范围从未超过一年,因此您的所有相关数据现在都具有同一年份,这是一个很好的分组标准
  3. 提取year 部分以将其用作组/分区标准
  4. 根据这个标准进行计算

【讨论】:

  • 感谢您的帮助和明确的答案。但我不明白两件事。 1. 为什么我不需要那几个月?而the_date这个是怎么定义的?
  • 1.您的要求是从六月到三月。所以你不需要四月和五月。当然你可以根据你的实际需求调整过滤器 2. 正如你在提供的小提琴中看到的那样,the_date 代表日期列
  • @hahakomisch 感谢您的接受。也请点赞,不胜感激:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多