【问题标题】:How to find the total sum of the least selling product for a particular month (irrespective of the year)如何找到特定月份(与年份无关)销量最低的产品的总和
【发布时间】:2019-04-03 08:42:39
【问题描述】:

我有一张表格,其中包含客户在特定日期购买的产品。我首先必须在所有 12 个月(无论年份)中找到桌子上销量最低的产品,然后找到该产品在该特定月份的总销售额(数量总和)。我已经完成了寻找不同 12 个月内销量最低的产品的第一部分。现在,如何找到该产品在该特定月份出现在表中的总数量。

查找所有 12 个月中最不受欢迎的产品的查询

with
    min_quant_table as (
        select distinct month, min(quant) as quant
        from myTable
        group by month
    )
select
    distinct month,
    prod as least_popular_prod,
    quant as least_popular_total_q
from min_quant_table
natural join myTable

输出(仅供参考):

Month        Least_Popular_Product          Least_Popular_Total_Sum_Quantity
1            Milk                           23126 
2            Eggs                           45514
3            Pepsi                          21457

这是查询的工作示例: http://sqlfiddle.com/#!9/4d756f/2

【问题讨论】:

  • 您的问题没有包含足够有用的详细信息,我们无法为您提供帮助。查看this post,然后根据需要编辑您的问题。
  • 感谢您添加小提琴!您标记了您的问题 postgresql 但您提供了 MySQL Fiddle。您实际使用的是哪一个?
  • 另外,鉴于您的小提琴中的数据,您能否显示您的预期输出?
  • 我在 PostgreSQL 里做。很抱歉,但我只需要提出查询的一般工作。

标签: sql postgresql


【解决方案1】:

我主要使用 T-SQL,但我认为 PostgreSQL 有窗口函数。您的查询看起来不错,我刚刚添加了 ROW_NUMBER() 函数并按给定月份的最小数量排序,然后为此选择了顶部选项。另外,我为每个产品在一个月内的数量添加了 SUM() 函数。

我认为以下内容应该不错,或者至少可以为您指明正确的方向。

;with min_quant_table as (
    select T.[prod]
    ,   T.[month]
    ,   MIN(T.quant) as min_quant
    ,   SUM(T.quant) as tot_quant
    ,   [rn] = row_number() over(partition by T.[month] order by min(T.quant))
    from #_tmp AS T
    group by T.prod, T.[month]
)
select abc.[month]
,   abc.[prod] as least_popular_prod
,   abc.min_quant as least_popular_min_q
,   abc.tot_quant as least_popular_total_q
from min_quant_table as abc
where abc.rn = '1'

那么你的输出将是这样的:

month   least_popular_prod  least_popular_min_q least_popular_total_q
1           Coke                    1557                    1557
2           Milk                    126                     126
3           Milk                    58                      58
4           Yogurt                  301                     1504
5           Milk                    1457                    1457
6           Yogurt                  363                     363
7           Yogurt                  17                      17
8           Milk                    1132                    1132
9           Bread                   42                      42
10          Yogurt                  730                     730
11          Milk                    210                     2632
12          Pepsi                   653                     7887

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 2018-11-26
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多