SQL重复减少,除以子查询结果的数量

时间:2014-02-07 05:41:11

标签: sql count duplicates divide

人!

我在这里遇到了一个问题。

我正在处理一些有很多重复的记录。每条记录都有三个键,一个是personID,CostCtr(成本中心)和工作位置。 一组这些重复记录可能如下所示:

PersonID    Cost Ctr    DaysInLocation  DaysInMonth
1111        256         3               28
1111        256         0               28
1111        256         3               28
1111        243         15              15
1111        243         15              15
1111        243         0               15

我想创建一个结果,将所有'daysInLocation'相加,并将其除以'daysInLocation'非0的计数,并添加所有daysInMonth除以daysInMonth的数量。

结果看起来像这样:

PersonID    CostCtr DaysInLocation  DaysInMonth
1111        256     3               28
1111        243     15              15

我也在寻找如何划分sum(stuff)/ count(子查询),其中sum(stuff)和Count(子查询)共享相同的personID,CostCtr和其他Key。

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?

select personid, costctr
       sum(daysinlocation) / sum(case when daysinlocation <> 0 then 1 else 0
                                 end) as DaysInLocation,
       sum(DaysInMonth) / count(DaysInMonth)
from table t
group by personid, costctr;

DaysInMonth表达式也可以是avg(DaysInMonth) as DaysInMonth