我需要按一列分组并从一个数据集中显示更多列

时间:2019-04-24 12:41:49

标签: sql database oracle

我有下表:

AMNT1   |  COLUMN1  |  COLUMN2  |  COLUMN3    | GROUP1
--------|-----------|-----------|-------------|--------
1.00    | COL1_ROW1 | COL2_ROW1 |   COL3_ROW1 | AAA
9.00    | COL1_ROW2 | COL2_ROW2 |   COL2_ROW2 | AAA
2.00    | COL1_ROW3 | COL2_ROW3 |   COL3_ROW3 | BBB
3.00    | COL1_ROW4 | COL2_ROW4 |   COL3_ROW4 | CCC

我想对GROUP1分组的AMNT1求和:

SELECT GROUP1, SUM(AMNT1) FROM ND_TEST GROUP BY GROUP1;

GROUP1 | SUM(AMNT1)
-------|-----------
AAA    | 10.00
BBB    | 2.00
CCC    | 3.00

另外,我想从一个行中选择COLUMN1,COLUMN2和COLUMN3。所以我的输出应该是这样的:

GROUP1 | SUM(AMNT1)|  COLUMN1  |  COLUMN2  |   COLUMN3  |
-------|-----------|-----------|-----------|------------|
AAA    | 10.00     | COL1_ROW1 | COL2_ROW1 |  COL3_ROW1 |
BBB    | 2.00      | COL1_ROW3 | COL2_ROW3 |  COL3_ROW3 |   
CCC    | 3.00      | COL1_ROW4 | COL2_ROW4 |  COL3_ROW4 |

如果在分区上使用总和,则每个组将得到重复...如果使用聚合函数,则不会从同一行中得到结果... 你有主意吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

select group1, sum_amnt1, column1, column2, column3
from   (
         select group1, sum(amnt1) over (partition by group1) as sum_amnt1, 
                column1, column2, column3,
                row_number() over (partition by group1 order by null) as rn
         from   your_table
       )
where  rn = 1
order by null函数中的

row_number()与您的澄清(在注释中)相对应,即来自每个组的任何行都可以(您不在乎哪个)

答案 1 :(得分:0)

您可以使用窗口功能:

select nt.*
from (select nt.*, sum(AMNT1) over (partition by GROUP1) as sum,
             row_number() over (partition by GROUP1 order by AMNT1) as seq
      from ND_TEST as nt
     ) nt
where seq = 1;