简体   繁体   English

如何在Oracle查询中显示聚合值和分类值?

[英]How do I Display Aggregated Values Alongside Disaggregated Values in an Oracle Query?

I have a simple table in Oracle that I want to group a certain way: I want to display disaggregated results alongside aggregated results in the same row. 我在Oracle中有一个简单的表,希望以某种方式进行分组:我想在同一行中显示汇总结果和汇总结果。 Here is the input table: 这是输入表:

常规表

with abc as
(
    select 'aaa' nnn, 100 amt from dual union
    select 'aaa', 20 from dual union
    select 'aaa', 3 from dual union
    select 'bbb', 44 from dual
)    
select * from abc

I want to display each individual row joined with a sum of the AMT column grouped by the NNN column. 我想显示与NMT列分组的AMT列总和相结合的每一行。 I don't know how to explain this, so here's what it'd look like: 我不知道该怎么解释,所以这是它的样子:

分组

The Sum column in a given row will equal the sum of the values of the AMT column for all of the rows with an NNN value equal to the NNN value in the same given row. 给定行中的Sum列等于所有行的AMT列值之和,其NNN值等于同一给定行中的NNN值。

I can do this by joining the input table with a grouped version of itself using the query below, but I think this is messy. 我可以使用下面的查询通过将输入表与自身的分组版本连接在一起来做到这一点,但是我认为这很麻烦。 My question is: Is there a builtin function in Oracle that accomplishes this? 我的问题是:Oracle中是否有内置功能可以实现这一目标? (My Oracle experience is a little weak, although I have lots of experience with SQL Server.) (尽管我在SQL Server方面有很多经验,但我的Oracle经验有些薄弱。)

with abc as
(
    select 'aaa' nnn, 100 amt from dual union
    select 'aaa', 20 from dual union
    select 'aaa', 3 from dual union
    select 'bbb', 44 from dual
)
select tblLeft.nnn, tblLeft.amt, tblRight.amtSum
from
(
    select nnn, amt from abc
) tblLeft
inner join
(
    select nnn, sum(amt) amtSum
    from abc
    group by nnn
) tblRight on tblLeft.nnn = tblRight.nnn

You could use analytic function to achieve your goal: 您可以使用分析功能来实现您的目标:

with abc as
(
    select 'aaa' nnn, 100 amt from dual union
    select 'aaa', 20 from dual union
    select 'aaa', 3 from dual union
    select 'bbb', 44 from dual
)    
select nnn,
       amt,
       sum(amt) over (partition by nnn)
  from abc;

Output: 输出:

NNN     AMT     SUM(AMT)OVER(PARTITIONBYNNN)
aaa     3       123
aaa     20      123
aaa     100     123
bbb     44      44

What analytic functions do: they allow you to use functions like SUM , but they calculate the value for each row instead of aggregating the result. 解析函数的作用:它们使您可以使用SUM之类的函数,但它们为每一行计算值,而不是汇总结果。 They have some other interesting options, if you would like to learn more: 如果您想了解更多信息,它们还有其他一些有趣的选项:

https://oracle-base.com/articles/misc/analytic-functions https://oracle-base.com/articles/misc/analytic-functions

SQLFiddle example SQLFiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM