将平均值添加到表中

Cha*_*les 2 sql t-sql sql-server

我有一张桌子

| Location | Unit | ...
+----------|------+----
| A        | 1    | ...
| A        | 1    | ...
| B        | 1    | ...
| A        | 2    | ...
| C        | 2    | ...
| ...      | ...  | ...
Run Code Online (Sandbox Code Playgroud)

我希望计算一个新表,其中包含每个单元的"平均"位置值,具体如下:

| Location | Unit | Weight |
+----------|------+--------+
| A        | 1    | 0.6667 |
| B        | 1    | 0.3333 |
| A        | 2    | 0.5    |
| C        | 2    | 0.5    |
| ...      | ...  | ...    |
Run Code Online (Sandbox Code Playgroud)

当然,获得总数很简单

select unit, location, count(*)
from table1
group by unit, location;
Run Code Online (Sandbox Code Playgroud)

并创建表

create table table2 (Unit nvarchar(50), Location int, Weight float);
Run Code Online (Sandbox Code Playgroud)

但我不确定如何用平均数据填充它.(这并不难,但不知怎的,我被卡住了......自从我在SQL Server上工作已经很多年了.)

Tho*_*ner 5

你会用到COUNT OVER这个:

select distinct
  location, unit, 
  cast(count(*) over (partition by unit, location) as decimal) / 
  cast(count(*) over (partition by unit) as decimal) as weight
from mytable
order by unit, location;
Run Code Online (Sandbox Code Playgroud)

SQLFiddle