Sql:客户在一段时间内订购产品的平均时间

时间:2012-02-27 10:53:27

标签: sql static average

如何计算产品在一周或一个月内平均销售的次数。

我对金额不感兴趣,但是客户购买给定产品的次数是多少。

订单行

 OrderNo | ProductNo | Amount |
----------------------------------------
       1 |         1 |     10 |
       1 |         4 |      2 |
       2 |         1 |      2 |
       3 |         1 |      4 |

顺序

     OrderNo | OrderDate
  ----------------------------------------
           1 | 2012-02-21
           2 | 2012-02-22
           3 | 2012-02-25

这是我正在寻找的输出

ProductNo | Average Orders a Week | Average Orders a month |
------------------------------------------------------------
        1 |                     3 |                     12 |
        2 |                     5 |                     20 |

2 个答案:

答案 0 :(得分:3)

您必须首先预先查询它,并按照您想要的平均方法进行计数。为了区分第1年和第2年,我会将事务的year()添加到分组限定符中以获得清晰度。例如2010年1月的销售额与2011年的销售额相比2012年的销售量相似,2010年第1周,2011年和2012年的第1周,而不是将所有3年计为一周。

如果您使用MySQL

,可以执行以下操作
select
      PreCount.ProductNo,
      PreCount.TotalCount / PreCount.CountOfYrWeeks as AvgPerWeek,
      PreCount.TotalCount / PreCount.CountOfYrMonths as AvgPerMonth,
      PreCount.TotalCount / PreCount.CountOfYears as AvgPerYear
   from
      ( select
              OL.ProductNo,
              count(*) TotalCount,
              count( distinct YEARWEEK( O.OrderDate ) ) as CountOfYrWeeks,
              count( distinct Date_Format( O.OrderDate, "%Y%M" )) as CountOfYrMonths,
              count( distinct Year( O.OrderDate )) as CountOfYears
           from
              OrderLine OL
                 JOIN Order O
                    on OL.OrderNo = O.OrderNo
           group by
              OL.ProductNo ) PreCount

答案 1 :(得分:1)

这是DRapp答案的副本,但是为SQL Server编码(对于评论来说太大了!)

SELECT PreCount.ProductNo,
       PreCount.TotalCount / PreCount.CountOfYrWeeks AS AvgPerWeek,
       PreCount.TotalCount / PreCount.CountOfYrMonths AS AvgPerMonth,
       PreCount.TotalCount / PreCount.CountOfYears AS AvgPerYear
FROM   (SELECT OL.ProductNo,
               Count(*) TotalCount,
               Count(DISTINCT Datepart(wk, O.OrderDate)) AS CountOfYrWeeks,
               Count(DISTINCT Datepart(mm, O.OrderDate)) AS CountOfYrMonths,
               Count(DISTINCT Year(O.OrderDate)) AS CountOfYears
        FROM   OrderLine OL  JOIN [Order] O
                 ON OL.OrderNo = O.OrderNo
        GROUP  BY OL.ProductNo) PreCount