将平均值添加到表中

时间:2014-11-04 15:14:08

标签: sql sql-server tsql

我有一张桌子

| Location | Unit | ...
+----------|------+----
| A        | 1    | ...
| A        | 1    | ...
| B        | 1    | ...
| A        | 2    | ...
| C        | 2    | ...
| ...      | ...  | ...

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

| Location | Unit | Weight |
+----------|------+--------+
| A        | 1    | 0.6667 |
| B        | 1    | 0.3333 |
| A        | 2    | 0.5    |
| C        | 2    | 0.5    |
| ...      | ...  | ...    |

当然,获得总数

非常简单
select unit, location, count(*)
from table1
group by unit, location;

并创建表

create table table2 (Unit nvarchar(50), Location int, Weight float);

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

3 个答案:

答案 0 :(得分: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;

SQLFiddle

答案 1 :(得分:2)

您想要加权平均值,单位为权重。您需要每个位置/单元组合的总和以及每个location的总和。要产生你的输出:

select location, unit, (1.0*unit) / sum(unit) over (partition by location)
from table1
group by location, unit;

如果1.0*实际上是一个整数,unit只是转换为十进制值的快捷方式。

编辑:

如果您只想要计数,那么这应该有效:

select location, unit, count(*) as cnt,
       (1.0*count(*)) / sum(count(*)) over (partition by unit)
from table1
group by location, unit;

答案 2 :(得分:0)

虽然你还没有说过有一个重量栏,但我假设必须有(否则,你的体重是什么意思?)

select unit, location, AVG(weight)
from table1
group by unit, location;

作为选择语句

select unit, location, AVG(weight)
into table2
from table1
group by unit, location;

作为插入新表