【问题标题】:How to apply partition on the table to get first data of each month?如何在表上应用分区以获取每个月的第一个数据?
【发布时间】:2023-01-25 20:54:01
【问题描述】:
CREATE TABLE employee
(
    joining_date date,
    employee_type character varying,
    name character varying ,
  typeid integer
);
insert into employee VALUES
    ('2021-08-12','as','hjasghg', 1),
    ('2021-08-13', 'Rs', 'sa', 1),
    ('2021-08-14','asktyuk','hjasg', 1),
  ('2021-09-12','as','hjasghg', 1),
    ('2021-09-13', 'Rs', 'sa', 1),
    ('2021-09-14','asktyuk','hjasg', 1),
  ('2022-08-02','as','hjasghg', 2),
    ('2022-08-03','as','hjasghg', 2),
    ('2022-08-04', 'Rs', 'sa', 2),
    ('2022-08-05','asktyuk','hjasg', 2);

我想获取包含每个月不同 typeid 的第一个数据读数的列。

我试过应用分区,但我似乎无法提取正确的数据。

【问题讨论】:

  • 请将您的尝试添加到问题中。还要添加查询的预期结果。

标签: sql postgresql


【解决方案1】:

demo:db<>fiddle

您可以将 DISTINCT ONdate_part() 函数结合使用

SELECT DISTINCT ON (typeid, date_part('month', joining_date))
    *
FROM employee
ORDER BY typeid, date_part('month', joining_date)
  1. date_part('month', ...) 将日期“规范化”为一个月的第一天(如果你愿意,也可以削减日期部分)
  2. DISTINCT ON 返回所有有序组中的第一个,在这种情况下,typeid 的组和您的规范化日期

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2011-03-18
    • 2017-05-17
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多