如何查找特定月份(与年份无关)中销售最少的产品的总金额

时间:2019-04-02 21:46:52

标签: sql postgresql

我有一个表,其中包含客户在特定日期购买的产品。我首先必须找到表上所有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

1 个答案:

答案 0 :(得分:0)

我主要使用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