在DB2中使用不同的group by语句

时间:2018-11-09 19:33:21

标签: sql db2 db2-400

我有一个成功的查询,该查询正在返回用户和类别的一些数据(该查询按类别和用户分组) 基本上是显示每个用户对每个类别的预测

select 
    user, 
    category, 
    sum(CatProjection) as CatProjection, 
    sum(CatProjection)/52 as WeekCatProjection
from projections
where user = 123
group by user, category

这将返回我想要/期望的内容:

USER  |   CATEGORY      |   CatProjection |  WeekCatProjection   
----------------------------------------------------------------
123   |   CategoryA     |   755000        |   14519              
123   |   CategoryB     |   390000        |   7500              
123   |   CategoryC     |   281250        |   5408              

问题是,这些结果按用户和类别分组,现在我想添加两列,这些列取决于该用户的CatProjection的总和,而不是按类别分组。

因此对于新值TotalCatProjection,我想添加该用户的所有CatProjection值。然后,我想使用CatPercentage将WeekCatProjection除以TotalCatProjection。

所以现在我期望这些结果:

USER  |   CATEGORY      |   CatProjection |  WeekCatProjection   |  TotalCatProjection |  CatPercentage 
--------------------------------------------------------------------------------------------------------
123   |   CategoryA     |   755000        |   14519              |  27427              |    52.94
123   |   CategoryB     |   390000        |   7500               |  27427              |    27.35
123   |   CategoryC     |   281250        |   5408               |  27427              |    19.72

当我的主要查询按用户AND类别分组时,如何获得这两个仅基于USER的新列?

1 个答案:

答案 0 :(得分:1)

由于DB2 7.3中引入了窗口函数,因此您应该使用子查询解决方案:

select user, 
    category, 
    CatProjection, 
    WeekCatProjection,
    TotalCatProjection,
    100 * WeekCatProjection / TotalCatProjection
from
(
    select 
        user, 
        category, 
        sum(CatProjection) as CatProjection, 
        sum(CatProjection)/52 as WeekCatProjection,
        ( 
           select sum(CatProjection) 
           from projections p2
           where p1.user = p2.user
        ) as TotalCatProjection
    from projections p1
    group by user, category 
) t

我避免使用where user = XYZ条件,因为这样GROUP BY user就没有意义了,但是,如果需要,您可以在其中插入它。