【问题标题】:How can I get the total of sales for the first month of each salesman如何获得每个业务员第一个月的总销售额
【发布时间】:2021-05-25 07:08:59
【问题描述】:

我使用 Postgresql,并且我有一个如下表所示的表格,我想知道每个人的第一个销售日期是什么以及当月的销售量。

Name Date_of_Sale Value
Mike 2019-11-13 $100
Dave 2019-11-17 $300
Charlie 2019-12-04 $150
Charlie 2019-12-19 $100
Dave 2019-11-11 $50
Mike 2019-12-01 $200

所以最终的结果是:

Name First sale Month Total Value
Mike 2019-11-13 2019-11 $100
Dave 2019-11-11 2019-11 $350
Charlie 2019-12-04 2019-12 $250

我使用了以下代码,但它并没有带回一个月。 提前致谢

FROM
(
select 
    name,
    to_char(min(date_of_sale), 'YYYY-MM-dd') as first_sale_date,
    concat (LPAD(extract('year' FROM date_of_sale)::text, 4, '0'), '-', LPAD(EXTRACT('month' FROM date_of_sale)::text, 2,'0') ,'-', '01') as month, 
    sum(value) as total_value

from 
    sales



group by 
    name,
    month
) as a
group by 
    name, date_first_sale, total_value´´´

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您可以使用distinct on 和聚合:

    select distinct on (name) name, min(date_of_sale), sum(value)
    from sales s
    group by name, date_trunc('month', date_of_sale)
    order by name, min(date_of_sale);
    

    如果你真的想要,你可以添加date_trunc('month', date_of_sale)。该查询返回最小日期,所以我不明白为什么还需要年/月。

    Here 是一个 dbfiddle。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-13
      • 2013-02-08
      • 1970-01-01
      • 2022-11-10
      • 2022-10-04
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多