SQL - 多个组的STDEVP

时间:2017-10-10 14:10:39

标签: sql ssms

我目前有一个查询可以让我按周使用某个项目:

SELECT Item, SUM(Quantity * PackQty) AS Usage
FROM [Database].[dbo].Transactions
WHERE Transactions.Type in ('I') AND Date > DATEADD(year, -1,GETDATE())
GROUP BY Item, Datepart(week, MyDate)
ORDER BY Item

它的输出是这样的:

**Item**   **Usage**
9999          10
9999          2
9999          1
9999          1
9999          1
9999          2
00125         5
00135         9
00135         10
00135         10
00159         2
00159         2
00159         6
00159         2
00159         4
00159         4
00159         4
00159         4
.....        ...

我想为人口使用的每个项目获得STDEVP。 例如,我想:

**Item**       **STDEVP**
9999             3.236
00125            0
00135            0.471  
00159            1.323
.....            .....

有没有办法实现这个目标?感谢

1 个答案:

答案 0 :(得分:0)

我认为这就是你想要的:

SELECT Item, SUM(Quantity * PackQty), STDEVP(Quantity * PackQty) AS Usage
FROM [Database].[dbo].Transactions
WHERE Transactions.Type in ('I') AND Date > DATEADD(year, -1,GETDATE())
GROUP BY Item
ORDER BY Item;

编辑:

如果您需要原始查询,请使用子查询:

SELECT Item, STDEVP(qp) AS Usage
FROM (SELECT Item, Datepart(week, MyDate) as myweek, SUM(Quantity * PackQty) as qp
      FROM [Database].[dbo].Transactions
      WHERE Transactions.Type in ('I') AND Date > DATEADD(year, -1, GETDATE())
      GROUP BY Item, Datepart(week, MyDate)
     ) iw
GROUP BY Item
ORDER BY Item;