我有下表:
MONTHNUMBER | MonthName | ProductName | QTY | AMOUNT | AVG qty/mos|
|-------------|-----------|-------------|-----|--------|------------|
| 1 | January | Thingamabob | 11 | 100.00 | |
| 1 | January | Widgets | 18 | 150.00 | |
| 2 | February | Thingamabob | 10 | 100.00 | |
| 2 | February | Widgets | 6 | 150.00 | |
| 3 | March | Thingamabob | 8 | 100.00 | |
| 3 | March | Widgets | 20 | 150.00 | |
| 4 | April | Thingamabob | 13 | 100.00 | |
| 4 | April | Widgets | 21 | 150.00 | |
| 5 | May | Thingamabob | 10 | 100.00 | |
| 5 | May | Widgets | 17 | 150.00 | |
是否可以获取每行MonthName的平均数量,并将其添加到AVG qty / mos列中?
我想要的桌子是这样的:
MONTHNUMBER | MonthName | ProductName | QTY | AMOUNT | AVG qty/mos|
|-------------|-----------|-------------|-----|--------|------------|
| 1 | January | Thingamabob | 11 | 100.00 | 14.5 |
| 1 | January | Widgets | 18 | 150.00 | 14.5 |
| 2 | February | Thingamabob | 10 | 100.00 | 8 |
| 2 | February | Widgets | 6 | 150.00 | 8 |
| 3 | March | Thingamabob | 8 | 100.00 | 14 |
| 3 | March | Widgets | 20 | 150.00 | 14 |
| 4 | April | Thingamabob | 13 | 100.00 | 16.5 |
| 4 | April | Widgets | 21 | 150.00 | 16.5 |
| 5 | May | Thingamabob | 10 | 100.00 | 13.5 |
| 5 | May | Widgets | 17 | 150.00 | 13.5 |
我尝试了以下脚本,并且得到的结果与QTY相同。
SUM(QTY)/COUNT(DISTINCT(MonthName))
我希望使用SQL可以做到这一点。
答案 0 :(得分:4)
您可以使用avg
窗口功能执行此操作。
select t.*,avg(qty) over(partition by monthnumber) as avg_qty_per_mnth
from tbl t
答案 1 :(得分:3)
您也可以在分区中使用monthname
select a.*,avg(QTY) over(partition by MonthName) as avgqty
from tab a
但是我认为最好同时使用month and year
和partition by
,因为
将来可能还需要您的哪一年的一月月份