同一查询中的总和联接列数据

时间:2019-05-27 20:11:32

标签: sql oracle

我正在使用Oracle DB,并具有以下引发错误的查询:

  

ORA-00937:不是单组分组功能

查询:

select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText';

如果我尝试单独访问以下内容,它将起作用。就像分别调用sum一样,分别是ct.CREAT_TS,依此类推。

问题似乎是在此查询中调用sum。我计划将输出捕获到对象(如果相关,则为Java)中。我希望查询输出如下。有可能做到这一点吗?

CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   8
2019-04-02 02:56:14.530000    SOME_EVENT 2

在给出答案之后,得到以下结果,其中总和值按列划分:

CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   2
2019-04-02 02:56:14.530000    SOME_EVENT 2   6

3 个答案:

答案 0 :(得分:1)

您需要包含group by子句。

select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText'
    group by ct.CREAT_TS, ev.EVENT;

答案 1 :(得分:1)

如果选择列表中至少存在一个聚合列,则需要按非聚合列进行分组

select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText'
    group by ct.CREAT_TS, ev.EVENT

答案 2 :(得分:1)

您可以使用窗口函数将总和放在每一行上:

your-command \
    | sort -V \
    | tail -n1 \
    | xargs basename

我不建议您仅将值放在一行上,但是您可以使用窗口函数来做到这一点:

select ev.EVENT, ct.CREAT_TS, sum(ct.TOT_CT), 
       sum(sum(ct.TOT_CT)) over ()
from REF_CT ct inner join
     EVENT ev
     on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
where ct.TX = 'SomeText'
group by ev.EVENT, ct.CREAT_TS;

如果您想要select ev.EVENT, ct.CREAT_TS, sum(ct.TOT_CT), (case when 1 = row_number() over (partition by ev.event order by ct.CREAT_TS) then sum(sum(ct.TOT_CT)) over () end) from REF_CT ct inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID where ct.TX = 'SomeText' group by ev.EVENT, ct.CREAT_TS order by ev.EVENT, ct.CREAT_TS; 定义的第一行的总计,order by非常重要。