SQL - 确定每月销售额的标准差

时间:2017-11-29 15:31:27

标签: sql sql-server

我有一张包含销售数据的表格,我正在尝试确定每月销售数量的标准差。但是,我一直收到错误:(

到目前为止,这是我的查询:

SELECT O.Id,
STDEV(COUNT(*)) OVER (ORDER BY YEAR(O.CreateDate), MONTH(O.CreateDate)) AS StdDeviation
FROM Orders O

我认为第二行需要最多的帮助。当我编译代码时,我收到错误:

  

'order'附近的语法不正确。

有什么想法吗? 我正在使用SQL Server Management Studio v17.2

这是我想要计算的一个例子。

示例

ID #7 might have 1 sale in January, 2 sales in February, 4 sales in March, etc.

我想分别为每个ID找到{1,2,4}的标准偏差。

预期输出示例:

Part Number  , Standard Deviation

1 , .86

2,  .83

1 个答案:

答案 0 :(得分:1)

首先计算每个月的计数,然后使用该计数来计算stdev,试试这个:

SELECT a.id, 
       Stdev(a.cnt) AS StdDeviation 
FROM   (SELECT O.id, 
               Year(O.createdate)  AS y, 
               Month(O.createdate) AS m, 
               Count(*)            AS cnt 
        FROM   orders o 
        GROUP  BY id, 
                  Year(O.createdate), 
                  Month(O.createdate)) a 
GROUP  BY id 

完整脚本

CREATE TABLE #temp (
  orderid int IDENTITY,
  CreateDate datetime,
  partid int

)


INSERT INTO #temp (CreateDate, partid)
  VALUES ('1/1/2017', 7),
  ('2/1/2017', 7),
  ('2/15/2017', 7),
  ('3/1/2017', 7),
  ('3/7/2017', 7),
  ('3/15/2017', 7),
  ('3/30/2017', 7),
  ('1/1/2017', 8),
  ('2/1/2017', 8),
  ('3/1/2017', 8),
  ('3/7/2017', 8),
  ('3/15/2017', 8)



SELECT
  a.partid,
  STDEV(a.cnt) AS StdDeviation
FROM (SELECT
  partid,
  YEAR(O.CreateDate) AS y,
  MONTH(O.CreateDate) AS m,
  COUNT(*) AS cnt
FROM #temp o
GROUP BY partid,
         YEAR(O.CreateDate),
         MONTH(O.CreateDate)) a
GROUP BY partid

DROP TABLE #temp